public class MyActivity extends ActionBarActivity {
Thread thread1,thread2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
thread1=new Thread(runnable1);
thread2=new Thread(runnable2);
thread1.start();
thread2.start();
}
Runnable runnable2=new Runnable() {
@Override
public void run() {
for (int i=0;i<30;i++)
try {
Thread.currentThread().sleep(1000);
System.out.println("THREAD 22222 ===>"+i);
if (i==6){
thread1.join();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Runnable runnable1=new Runnable() {
@Override
public void run() {
//while(thread2flag){
for (int i=0;i<8;i++)
try {
Thread.currentThread().sleep(1000);
System.out.println("THREAD 111111 ===>"+i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
}
Thread.join在哪裏調用,誰調用誰就等待被join的線程的結束後再執行。
同時啓動兩個線程,進行消息打印,若是沒有join方法的干預,通常來講,二者輪番搶cpu,誰搶到了誰執行,二者爭到cpu機率同樣大。當線程2執行到i==6的時候,霸王來了,也沒準,不是沒準確實是線程2自願的,發揚紳士風度,在本身內調用線程1的join方法,那麼此時線程2就停在那裏了,把cpu使用權(暫且這麼說吧,也不知合不合理)給了線程1,此時線程1愉快歡唱屁顛屁顛樂呵樂呵絕不客氣的執行完了本身的操做,而後線程2默默地望着線程1遠去的背影,開始繼續本身的執行旅程。純屬我的理解,如有異議,歡迎批評指正。