线程合并状态join
join的特点:
-
join插队线程,待此线程执行完毕后再执行其他线程
-
在此期间其他线程阻塞
join与sleep方法的区别:
-
join是一个成员方法,join要通过Thred对象操作--->对象要多次使用,所以不要用匿名
-
sleep和yield是一个静态方法
join实例
package iostudy.threadstate;
/**
* join合并线程,插队线程
* @since JDK 1.8
* @date 2021/6/5
* @author Lucifer
*/
public class BlockedJoinNo4 {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(() -> {
for (int i = 0; i < 100; i++){
System.out.println("lambda!!!!!!" + i);
}
});
/*通过对象使用--->join方法是成员方法*/
t.start();
for (int i = 0; i < 100; i++){
if (i == 20){
t.join(); //形参可以传时间--->表示时间到了还未插入的话就直接跳过。
/*
此时main主线程被阻塞
其结果是当main为20时候
main线程会等待lambda执行完毕再执行main线程--->插入
*/
}
/*输出main*/
System.out.println("main is:" + i);
}
}
}
-
搞清楚是哪个线程被阻塞
-
之前的sleep和yield都是随机等待cpu调度,而join方法有点类似于方法的调用
join实例2
package iostudy.threadstate;
/**
* join插入线程,等待
* @since JDK 1.8
* @date 2021/6/5
* @author Lucifer
*/
public class BlockedJoinNo2 {
public static void main(String[] args) throws InterruptedException{
System.out.println("Father and Son's story");
/*新建线程对象*/
new Thread(new Father()).start();
}
}
/**
* 写一个父亲类,继承Thread类
*/
class Father extends Thread{
/*重写run方法*/
public void run(){
System.out.println("Want to smoke but no have cigarettes!!!");
System.out.println("Tell son to buy cigarettes");
/*
1、创建代理类对象--->new Thread
2、创建实现类对象--->new Son
3、通过Thread对象调用方法--->为了线程插入
*/
Thread t = new Thread(new Son());
t.start(); //从这里开始进入到Son类的方法当中
/*
如果这里不加入join插入的话
会直接执行后面的语句而不是等待Son类执行方法
所以这里要加入join
*/
try {
t.join();
/*
1、必须等待Son类线程执行完毕以后Father才能执行
2、此时的join写在Father的线程体中
3、Father被阻塞
*/
System.out.println("Continue smoking!!!");
}catch (InterruptedException e){
System.out.println(e.getMessage());
e.printStackTrace();
System.out.println("Find son!!!");
}
}
}
/**
* 写一个儿子类,继承Thread
*/
class Son extends Thread{
/*重写run方法*/
public void run(){
System.out.println("Take money to buy cigarettes!!!");
System.out.println("Play game ten hours!!!");
for (int i = 0; i < 10; i++){
System.out.println(i + "秒过去了!!!");
/*玩就是线程等待的意思*/
try {
/*线程阻塞10s*/
Thread.sleep(1000);
}catch (InterruptedException e){
System.out.println(e.getMessage());
e.printStackTrace();
}
}
System.out.println("继续做事情!!!");
}
}