在调用线程的sleep方法时,线程直接结束了是怎么回事?

下面是代码:

    @Test
    public void test03() throws Exception {
        // 启动线程
        new Thread(MyServer::run, "Th01").start();
    }


class MyServer {
    private static int total = 10;

    public static synchronized void run() {
        try {
            for (int i = 1; i < total; i++) {
                System.out.println(Thread.currentThread().getName() + " :" + i);
                Thread.sleep(1000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

本来预期应该能把1到10都打出来,但是debug时发现运行到sleep时直接线程终止了。。。

如果去掉sleep方法就能正常打印完,大佬们这是怎么回事啊?求解,谢谢!

有可能是unitTest在调用完所有test方法之后使用诸如System.exit(0)之类的东西强制退出了主线程,于是就造成子线程终止,可以尝试对Th01线程调用join方法让主线程等待它结束后才能退出试试。

Thread th01 = new Thread(MyServer::run, "Th01");
th01.start();
th01.join();

 

class MyServer {
	private static int total = 10;

	public static synchronized void run() {
		try {
			for (int i = 1; i < total; i++) {
				System.out.println(Thread.currentThread().getName() + " :" + i);
				Thread.sleep(1000);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

public class ThreadDemo {
	public static void main(String[] args) {
		new Thread(MyServer::run, "Th01").start();
	}

}

Th01 :1
Th01 :2
Th01 :3
Th01 :4
Th01 :5
Th01 :6
Th01 :7
Th01 :8
Th01 :9
 

本来预期是能打出1到10的,但现在只打出第一个。

Th01 :1
Th01 :2
Th01 :3
Th01 :4
Th01 :5
Th01 :6
Th01 :7
Th01 :8
Th01 :9