简体   繁体   English

如果Thread.sleep是静态的,那么各个线程如何知道它被置于睡眠状态?

[英]if Thread.sleep is static, how does individual thread knows it is put to sleep?

I am a bit confused with Thread.sleep() method. 我对Thread.sleep()方法有点困惑。 if Thread.sleep() is a static method, how does two threads know which is put to sleep. 如果Thread.sleep()是一个静态方法,两个线程如何知道哪些线程进入休眠状态。 For example, in the code below, I have two three Threads main , t and t1 . 例如,在下面的代码中,我有两个三个Threads maintt1 I call Thread.sleep() always. 我总是调用Thread.sleep() Not t.sleep() . 不是t.sleep() Does it mean Thread.sleep() puts the current Thread to sleep? 这是否意味着Thread.sleep()将当前线程置于睡眠状态? That means a Thread instance puts to sleep by itself by calling the static method. 这意味着Thread实例通过调用静态方法自行进入休眠状态。 what if t1 wants to put t to sleep. 如果T1想要把t睡觉。 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? 这是否意味着Thread.sleep()将当前线程置于睡眠状态?

Yes. 是。 Only the current thread can do that. 只有当前线程可以做到这一点。

What if t1 wants to put t to sleep. 如果t1想要睡觉怎么办? 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标志,该标志将导致另一个线程调用Thread.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() . 它可以从Thread.currentThread()找到当前线程。 The current thread only can put itself to sleep. 当前线程只能让自己进入睡眠状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM