1

我想测试 Thread.sleep() 方法,我发现了一个有趣的事情。当我调用 main() 方法时,控制台会打印“UserA sleep...”和“UserA waking...”,这意味着程序被唤醒,但是当我使用 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();
        }

    }
}
4

1 回答 1

2

我的猜测是,JUnit 在睡眠完成之前拆除了测试,因为测试执行线程在睡眠完成之前退出了测试方法。尝试

@Test
public void testWakeup() throws Exception {
    Thread t = new Thread(new UserA());
    t.start();
    t.join();
}
于 2013-08-24T02:43:49.667 回答