thread join

来源:互联网 发布:剑三帅气成男脸型数据 编辑:程序博客网 时间:2024/05/21 22:29
package thread.demo01;public class ThreadJoinExample{public static void main(String[] args){Thread t1 = new Thread(new MyRunnable(), "t1");Thread t2 = new Thread(new MyRunnable(), "t2");Thread t3 = new Thread(new MyRunnable(), "t3");t1.start();// start second thread after waiting for 2 seconds or if it's deadtry{t1.join(2000);}catch (InterruptedException e){e.printStackTrace();}t2.start();// start third thread only when first thread is deadtry{t1.join();}catch (InterruptedException e){e.printStackTrace();}t3.start();// let all threads finish execution before finishing main threadtry{t1.join();t2.join();t3.join();}catch (InterruptedException e){e.printStackTrace();}System.out.println("All threads are dead, exiting main thread");}}class MyRunnable implements Runnable{@Overridepublic void run(){System.out.println("Thread started:::" + Thread.currentThread().getName());try{Thread.sleep(4000);}catch (InterruptedException e){e.printStackTrace();}System.out.println("Thread ended:::" + Thread.currentThread().getName());}}
Thread started:::t1Thread started:::t2Thread ended:::t1Thread started:::t3Thread ended:::t2Thread ended:::t3All threads are dead, exiting main thread.
 
原创粉丝点击