如果Thread.sleep是静态的,那么各个线程如何知道它被置于睡眠状态? [英] if Thread.sleep is static, how does individual thread knows it is put to sleep?
问题描述
我对 Thread.sleep()
方法感到困惑。 if Thread.sleep()
是一个静态方法,两个线程如何知道哪个线程处于休眠状态。例如,在下面的代码中,我有两个三主题
主
, t
和 t1
。我总是打电话给 Thread.sleep()
。不是 t.sleep()
。这是否意味着Thread.sleep()将当前线程置于睡眠状态?这意味着Thread实例通过调用静态方法自行进入休眠状态。如果t1想要让 t
进入睡眠状态怎么办?这应该不正确吗?
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.");
}
}
推荐答案
是否意味着Thread.sleep()将当前线程置于休眠状态?
Does it mean Thread.sleep() puts the current Thread to sleep?
是。只有当前线程可以做到这一点。
Yes. Only the current thread can do that.
如果t1想让t进入睡眠状态怎么办?那不应该是正确的吗?
What if t1 wants to put t to sleep. that shouldn't be possible correct?
对。您可以设置一个 volatile boolean
标志,该标志将导致另一个线程调用 Thread.sleep(...)
但另一个线程不能导致线程休眠。
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(...);
}
这篇关于如果Thread.sleep是静态的,那么各个线程如何知道它被置于睡眠状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!