join是Thread类中的方法
让两个并行的线程变成单线程
join()可以传递毫秒值作为参数
主方法:
public class Test {
public static void main(String[] args){
ThreadOne threadOne = new ThreadOne();
threadOne.start();
}
}
ThreadOne类:
public class ThreadOne extends Thread{
public void run(){
System.out.println("ThreadOne start");
ThreadTwo threadTwo = new ThreadTwo();
threadTwo.start();
try {
threadTwo.join(2000);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("ThreadOne end");
}
}
ThreadTwo类
public class ThreadTwo extends Thread{
public void run(){
System.out.println("ThreadTow start");
ThreadThree threadThree = new ThreadThree(this);
threadThree.start();
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("ThreadTwo end");
}
}
ThreadThree类
public class ThreadThree extends Thread{
public ThreadThree(ThreadTwo threadTwo){
this.threadTwo = threadTwo;
}
private ThreadTwo threadTwo;
public void run(){
System.out.println("ThreadThree start");
// 在threadTwo执行的过程中,threadOne等待的过程中,threadThree将threadTwo对象锁定
synchronized(threadTwo){
System.out.println("ThreadTwo is locked");
try{
Thread.sleep(5000);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("ThreadTwo is freed");
}
System.out.println("ThreadThree end");
}
}
运行结果: