菜鸟学习笔记,高手绕过,不喜勿喷。
先上代码:
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 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远去的背影,开始继续自己的执行旅程。纯属个人理解,若有异议,欢迎批评指正。