主线程调用子线程对象的 sleep() 方法,会造成子线程睡眠吗?

前言

今天在写线程测试的时候,写下了如下的一段代码

public class ThreadTests {
	
[@Test](https://my.oschina.net/azibug)
public void test_thread_sleep() throws InterruptedException {
	Thread t = new Thread(new MyRunnable());
	t.start();
	t.sleep(10000);
	while(true)
		System.out.println("main thread");
}

public class MyRunnable implements Runnable{

	[@Override](https://my.oschina.net/u/1162528)
	public void run() {
		System.out.println("son thread");
	}

}

}

结果测试之后,并没有按照我预想的那样执行。即打印 10 s的 “main thread”,然后打印出 “son thread”。 而实际执行结果是主线程阻塞了 10s,然后一直打印 “main thread”。

分析

sleep() 方法 是 Thread 类中的一个静态方法,跟调用他的对象无关,而是跟在哪个线程调用他有关系,因此在主线程调用 t.sleep(); 方法实际上等于调用 Thread.sleep() 。同时也就造成主线程阻塞 10 s。

如何让子线程睡眠

从上面的分析中可以得出如下用法:

public class ThreadTests {

	[@Test](https://my.oschina.net/azibug)
	public void test_thread_sleep() throws InterruptedException {
		Thread t = new Thread(new MyRunnable());
		t.start();
		//t.sleep(10000);
		while(true)
			System.out.println("main thread");
	}

	public class MyRunnable implements Runnable{

		[@Override](https://my.oschina.net/u/1162528)
		public void run() {
			try {
				Thread.currentThread().sleep(10);// 在子线程的 run() 方法里调用sleep() 方法
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("son thread");
		}

	}
}

转载于:https://my.oschina.net/u/3984985/blog/3024813

你可能感兴趣的:(主线程调用子线程对象的 sleep() 方法,会造成子线程睡眠吗?)