线程1中启动线程2,线程2阻塞,那么会执行线程3,线程3完成后会出栈线程2,线程2接着运行,最后接着运行线程1.
线程1.join()方法是立即获得cpu并且等待线程1执行完成才继续往下运行。
线程1.start()方法是等待当前线程运行完后或者阻塞再去运行线程1。
关于线程套娃,线程一启动线程2,线程一阻塞,然后线程2中启动线程一,然后线程2阻塞,那么run方法中阻塞后面的函数永远也不会执行。只要注意好阻塞就可以疯狂挑战cpu。
阻塞队列poll方法中的参数超时时间也会阻塞当前运行线程,具体情况具体分析。
线程在死亡,阻塞或者run完成才会跳转去执行别的线程。
下图代码可以灵活测试:
package com.example.testlib;
import java.lang.Thread;
public class MytestClass {
static class ThreadMsgBusyDeal extends Thread{
public static class test1 implements Runnable{
public void run(){
System.out.println("test2");
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void run() {
for(int i=0;i<10;i++){
System.out.println("i:"+i);
}
test1 mystart=new test1();
Thread t1=new Thread(mystart,"huoche");
t1.start();//等待当前线程运行完成后再运行
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
for(int a=20;a<30;a++){
System.out.println("a:"+a);
}
}
}
public static void main(String []args) {
ThreadMsgBusyDeal testthread=new ThreadMsgBusyDeal();
testthread.start();
//java 8所支持
new Thread(()->{
System.out.println("this is a new function !");
}).start();
}
}
结果:
> Task :testlib:MytestClass.main()
i:0
i:1
i:2
i:3
i:4
i:5
i:6
i:7
i:8
i:9
test2
this is a new function !
a:20
a:21
a:22
a:23
a:24
a:25
a:26
a:27
a:28
a:29