join()与sleep()不同的是join()是成员方法,sleep()是Thread.sleep(),join()必须通过Thread对象才能点join()。写在哪个线程体中,当前的那个线程体就被阻塞了。
package com.sxt.state;
/**
* join 合并线程 插队线程
*
* @author yanghai
*
*/
public class BlockedJoin01 {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(() -> {
for (int i = 0; i < 100; i++) {
System.out.println("lambda-->" + i);
}
});
t.start();
for (int i = 0; i < 100; i++) {
if (i == 20) {
t.join();// 插队 main被阻塞了
}
System.out.println("main-->" + i);
}
}
}
package com.sxt.state;
/**
* join 合并线程 插队线程
*
* @author yanghai
*
*/
public class BlockedJoin02 {
public static void main(String[] args) throws InterruptedException {
System.out.println("爸爸和儿子买烟的故事");
// new Father().start();
new Thread(new Father()).start();
}
}
class Father extends Thread {
@Override
public void run() {
System.out.println("爸爸想抽烟,发现烟没了。");
System.out.println("让儿子去买烟");
// Son t = new Son();
Thread t = new Thread(new Son());
t.start();
try {
t.join();
System.out.println("爸爸拿过烟,把零钱给了儿子");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Son extends Thread {
@Override
public void run() {
System.out.println("儿子拿着钱去买烟。");
System.out.println("路过一家游戏厅,玩了10秒钟");
for (int i = 1; i <= 10; i++) {
try {
Thread.sleep(1000);
System.out.println("过去了" + i + "秒");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("拿着烟回家去");
}
}