문제

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

@Test
public void testWakeup() throws Exception {
    Thread t = new Thread(new UserA());
    t.start();
    t.join();
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top