Java多线程(十)线程间通信 join

时间:2024-09-06 15:35:02

若果主线程想等待子线程执行完成之后再结束,可以用join方法

join 和sleep区别 join内部有wait实现,所以当执行join方法后,当前线程的锁被释放,那么其他线程就可以调用此线程的同步方法了。

public class Run {

    public static void main(String[] args) throws InterruptedException {
MyThread myThread = new MyThread();
myThread.start();
myThread.join(1000);
//Thread.sleep(1000);
System.out.println(" end time=" + System.currentTimeMillis());
}
}

MyThread

public class MyThread extends Thread{

    public void run(){
try {
System.out.println("begin time="+System.currentTimeMillis());
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}