我想测试Thread.sleep()方法,我发现了一个有趣的事情.. 当我调用 main() 方法时,控制台将打印“UserA sleep...”和“UserA wakeing...”,这意味着程序被唤醒,但是当我使用 junit 方法运行与 main() 相同的代码时)方法,它不会打印“UserA waking...”...我将不胜感激任何人都可以解释它。
package com.lmh.threadlocal;
import org.junit.Test;
public class ThreadTest {
public static void main(String [] args) {
new Thread(new UserA()).start();
}
@Test
public void testWakeup(){
new Thread(new UserA()).start();
}
}
class UserA implements Runnable{
@Override
public void run() {
try {
System.out.println("UserA sleeping...");
Thread.sleep(1000);
System.out.println("UserA waking...");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
最佳答案
我的猜测是,JUnit 在 sleep 完成之前拆除测试,因为测试执行线程在 sleep 完成之前退出测试方法。尝试一下
@Test
public void testWakeup() throws Exception {
Thread t = new Thread(new UserA());
t.start();
t.join();
}
关于java - 为什么无法唤醒该线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18414327/