سؤال

I am a bit confused with Thread.sleep() method. if Thread.sleep() is a static method, how does two threads know which is put to sleep. For example, in the code below, I have two three Threads main, t and t1. I call Thread.sleep() always. Not t.sleep(). Does it mean Thread.sleep() puts the current Thread to sleep? That means a Thread instance puts to sleep by itself by calling the static method. what if t1 wants to put t to sleep. that shouldn't be possible correct?

public class ThreadInterrupt {

    public static void main(String[] args) throws InterruptedException {

        System.out.println("Starting.");

        Thread t  = new Thread(new Runnable(){

            @Override
            public void run() {
                Random ran = new Random();

                for (int i = 0; i < 1E8; i++) {

                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        System.out.println("we have been interrupted");
                        e.printStackTrace();
                    }
        });

        Thread t2 = new Thread(new Runnable() {
                 public void run() {
                         //some stuff
                 }
        });    
        t.start();
        t2.start();

        Thread.sleep(500);
        t.interrupt();
        t.join();

        System.out.println("Finished.");
    }

}
هل كانت مفيدة؟

المحلول

Does it mean Thread.sleep() puts the current Thread to sleep?

Yes. Only the current thread can do that.

What if t1 wants to put t to sleep. that shouldn't be possible correct?

Right. You can set a volatile boolean flag that will cause another thread to call Thread.sleep(...) but another thread can't cause a thread to sleep.

 volatile boolean shouldSleep = false;
 ...
 // check this flag that might be set by another thread to see if I should sleep
 if (shouldSleep) {
     Thread.sleep(...);
 }

نصائح أخرى

It can find the current thread from Thread.currentThread(). The current thread only can put itself to sleep.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top