I want to test Thread.sleep() method, and I found a interesting thing.. When I invoke main() method , the console will print "UserA sleeping..." and "UserA waking...", that means the program is awakened , but when I use a junit method to run the same code as main() method, it won't print "UserA waking..." ... I will be appreciate anyone can explain it .
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();
}
}
}
My guess is that JUnit is tearing down the test before the sleep finishes, because the test execution thread exits the test method before the sleep finishes. Try