Why can't wake up this thread

156 views Asked by At

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();
        }

    }
}
1

There are 1 answers

3
sjr On BEST ANSWER

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

@Test
public void testWakeup() throws Exception {
    Thread t = new Thread(new UserA());
    t.start();
    t.join();
}