标签:except package todo start ack for interrupt his catch
package com.cn.test.thread; public class TestJoin extends Thread{ private String name; public TestJoin(String name) { this.name = name; } public static void main(String[] args) { TestJoin join1 = new TestJoin("thread-1"); TestJoin join2 = new TestJoin("thread-2"); join1.start(); join2.start(); try { join1.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("main--------------------线程"); } @Override public void run() { for (int i=0; i<3; i++) { System.out.println(Thread.currentThread().getName() + "i=" + i) ; } } }
上述例子中: 在main方法中join1线程调用join方法,如果main方法抢到cpu的执行权,会将cpu的执行权让出来给join1线程,直到join1线程执行完毕之后才进行main线程的执行。join1和join2是同步进行竞争cpu的资源。
运行结果:
Thread-0i=0 Thread-1i=0 Thread-0i=1 Thread-1i=1 Thread-0i=2 Thread-1i=2 main--------------------线程
main线程需要等待join1线程执行完毕之后才能进行执行
Thread的join方法在start方法之前进行执行,不会触发这种cpu让出执行权的操作,此时和mian线程是并发执行的。
package com.cn.test.thread; public class TestJoin extends Thread{ private String name; public TestJoin(String name) { this.name = name; } public static void main(String[] args) { TestJoin join1 = new TestJoin("thread-1"); TestJoin join2 = new TestJoin("thread-2"); try { join1.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } join1.start(); join2.start(); System.out.println("main--------------------线程"); } @Override public void run() { for (int i=0; i<3; i++) { System.out.println(Thread.currentThread().getName() + "i=" + i) ; } } }
执行结果:
main--------------------线程 Thread-1i=0 Thread-1i=1 Thread-1i=2 Thread-0i=0 Thread-0i=1 Thread-0i=2
总结:join方法可以控制多线程的执行顺序。
标签:except package todo start ack for interrupt his catch
原文地址:https://www.cnblogs.com/startSeven/p/10213645.html