多线程_插队join

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("拿着烟回家去");
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值