gpt4 book ai didi

java - 如果 Thread.sleep 是静态的,单个线程如何知道它已进入休眠状态?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:45:01 26 4
gpt4 key购买 nike

我对 Thread.sleep() 方法有点困惑。如果 Thread.sleep() 是静态方法,两个线程如何知道哪个线程进入休眠状态。例如,在下面的代码中,我有两个三个 Threadsmaintt1。我总是调用 Thread.sleep()。不是 t.sleep()。这是否意味着 Thread.sleep() 使当前线程进入休眠状态?这意味着 Thread 实例通过调用静态方法自行进入休眠状态。如果 t1 想让 t 进入休眠状态怎么办?这不可能是正确的?

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?

是的。只有当前线程可以这样做。

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

没错。您可以设置一个 volatile boolean 标志,这将导致另一个线程调用 Thread.sleep(...) 但另一个线程不能导致线程 hibernate 。

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

关于java - 如果 Thread.sleep 是静态的,单个线程如何知道它已进入休眠状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22104283/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com