thread.join的含义是当前线程需要等待previousThread线程终止之后才从thread.join返回。简单来说,就是线程没有执行完之前,会一直阻塞在join方法处。
package comTow.thread8;
/**
* description: JoinDemo
* date: 2020/2/6 9:58
* author: WHF
* version: 1.0
*/
public class JoinDemo extends Thread {
int i;
Thread previousThread; //上一个线程
public JoinDemo(Thread previousThread,int i)
{
this.previousThread=previousThread;
this.i=i;
}
@Override
public void run() {
try {
previousThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("num:"+i);
}
public static void main(String[] args) {
Thread previousThread=Thread.currentThread();
for (int i=0;i<10;i++)
{
JoinDemo joinDemo=new JoinDemo(previousThread, i);
joinDemo.start();
previousThread=joinDemo;
}
}
}
运行结果:
num:0
num:1
num:2
num:3
num:4
num:5
num:6
num:7
num:8
num:9
public class ThreadJion2 {
public static void main(String[] args) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
final Thread t1=new Thread(){
@Override
public void run() {
System.out.println("t1 is running");
while (true)
{
if (Thread.currentThread().isInterrupted()==true)
{
System.out.println("Thread.currentThread().isInterrupted() true");
break;
}
}
}
};
t1.start();
Thread t2=new Thread(new Runnable(){
@Override
public void run() {
try {
Thread.sleep(10000);
t1.interrupt();
System.out.println(" t1 is interrupt");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t2.start();
try {
t1.join(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
运行结果:
t1 is running
t1 is interrupt
Thread.currentThread().isInterrupted() true