经常有人会问:如何停止一个线程?线程类Thread
的join
、sleep
、interrupt
等方法的具体使用场景是什么?本文就线程的join
和sleep
方法来看一下具体场景下的表现。
方法定义
join
先看下源码
/**
* Waits for this thread to die.
*
* <p> An invocation of this method behaves in exactly the same
* way as the invocation
*
* <blockquote>
* {@linkplain #join(long) join}{@code (0)}
* </blockquote>
*
* @throws InterruptedException
* if any thread has interrupted the current thread. The
* <i>interrupted status</i> of the current thread is
* cleared when this exception is thrown.
*/
public final void join() throws InterruptedException {
join(0);
}
源码中提示:Waits for this thread to die.顾名思义,等待线程死亡。
而且该方法会抛出中断异常
那么具体会产生什么效果呢?我们来验证一下。
以下代码是在主线程循环体内部调用其他线程的join
方法,其他线程单纯的打印执行结果
/**
* 程序入口,主线程
*/
public static void main(String[] args) {
Thread thread = new Thread(new PrintTask("Thread"));
thread.start();
for (int i = 0; i < 1000; i++) {
if (i == 500) {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println("程序结束");
}
/**
* 子线程任务
*/
private static class PrintTask implements Runnable {
private String name;
public PrintTask(String name) {
this.name = name;
}
@Override public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println(name + " ------> " + i);
}
System.out.println("-----thread finished. -----");
}
}
执行以上main
方法,输出为:
Thread ------> 995
Thread ------> 996
Thread ------> 997
Thread ------> 998
Thread ------> 999
-----thread finished. -----
程序结束
可以看出,主线程中调用其他线程的join
后,必须等待其他线程的结束,才可以继续执行。
也就是说:
自身线程内,他线程join。自身需要等待他线程结束后才会获得执行,影响自身
稍微改动一下,将主线程的join
操作移动到其他线程执行体内。
/**
* 程序入口,主线程
*/
public static void main(String[] args) {
Thread thread = new Thread(new PrintTask("Thread"));
thread.start();
for (int i = 0; i < 1000; i++) {
// 让主线程不要太快结束
Math.random();
}
System.out.println("程序结束");
}
private static