线程中,join方法用来保障线程的执行顺序~
public class DateSource implements Runnable { public void run() { // TODO Auto-generated method stub System.out.println("begin DateSource " + new Date()); try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("begin DateSource " + new Date()); } public static void main(String []args){ DateSource ds = new DateSource(); ConnectionDataSource cd = new ConnectionDataSource(); Thread thread1 = new Thread(ds); Thread thread2 = new Thread(cd); thread1.start(); try { // 在执行线程2之前把线程1run方法内代码全部执行完成,在执行线程2 thread1.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } thread2.start(); } }
public class ConnectionDataSource implements Runnable { public void run() { // TODO Auto-generated method stub System.out.println("begin ConnectionDataSource " + new Date()); try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("begin ConnectionDataSource " + new Date()); } }
在没有加入thread1.join();线程执行是无序的大家应该都知道,加入thread1.join();就是先保障它先执行完成
执行结果
begin DateSource Wed Oct 14 14:38:55 CST 2015 begin DateSource Wed Oct 14 14:38:58 CST 2015 begin ConnectionDataSource Wed Oct 14 14:38:58 CST 2015 begin ConnectionDataSource Wed Oct 14 14:39:01 CST 2015
主线程向下转时,碰到了thread1.join(),thread1要申请加入到运行中来,就是要CPU执行权。这时候CPU执行权在主线程手里,主线程就把CPU执行权给放开,陷入冻结状态。活着的只有thread1了,只有当thread1拿着执行权把这些数据都打印完了,主线程才恢复到运行中来。
join方法可以用于临时加入线程,一个线程在运算过程中,如果满足于条件,我们可以临时加入一个线程,让这个线程运算完,另外一个线程再继续运行。
如果将thread1.join()和thread2.start()位置互换,又会怎样呢?主线程开启了thread1、thread2,这时候CPU执行权还在主线程手里。当主线程碰到了thread1.join(),释放执行权,处于冻结状态。活着的thread1、thread2都具备执行资格,这时候CPU便对thread1和thread2交替执行。主线程要等到thread1结束才能活,至于thread2结不结束,与主线程没有丝毫关系。如果thread1结束了,thread2还没结束,主线程就会和thread2抢执行权执行。主线程碰到谁的join,它就等谁。也就是说,谁让它把执行权放出来,它就等谁执行完毕后。至于谁去抢,它不管。