线程相关

 CountDownLatch的用法:开一个线程可以等待其他所有线程完事之后再执行,注意等待的线程数目的大小

示例代码如下:

public class Solution {

	public static void main(String[] args) throws InterruptedException {
		ExecutorService executor = Executors.newCachedThreadPool();

		CountDownLatch latch = new CountDownLatch(2);
		Worker w1 = new Worker(latch, "张三");
		Worker w2 = new Worker(latch, "李四");
		Worker w3 = new Worker(latch, "王二");

		ArrayList<Worker> al = new ArrayList<>();
		al.add(w1);
		al.add(w3);
		al.add(w2);
		Boss boss = new Boss(latch);

		Thread t1 = new Thread(boss);
		t1.start();
		for (Worker worker : al) {
			 Thread.sleep(500);
			executor.execute(worker);
		}
		// executor.execute(w1);
		// executor.execute(w2);
		// executor.execute(w3);
		// executor.execute(boss);

		executor.shutdown();
	}
}

class Worker implements Runnable {
	private String name;
	private CountDownLatch downLatch;

	Worker(CountDownLatch downLatch, String name) {
		this.name = name;
		this.downLatch = downLatch;
	}

	@Override
	public void run() {
		try {
			System.out.println(this.name + "正在干活!");
			Thread.sleep(1);
			System.out.println(Thread.currentThread().getName() + "  " + this.name);

			// TimeUnit.SECONDS.sleep(new Random().nextInt(10));
		} catch (InterruptedException ie) {
		}
		System.out.println(this.name + "活干完了!");
		this.downLatch.countDown();
	}
}

class Boss implements Runnable {
	private CountDownLatch downLatch;

	Boss(CountDownLatch downLatch) {
		this.downLatch = downLatch;
	}

	@Override
	public void run() {
		System.out.println("老板开始检查了,但是所有人的活没干完");
		try {
			this.downLatch.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("所有人的活都干完了!,老板可以检查");
	}

}


 BlockingQueue,阻塞队列:当一个线程试图对一个已经满了的队列进行入队列操作时,它将会被阻塞,除非有另一个线程做了出队列操作;同样,当一个线程试图对一个空队列进行出队列操作时,它将会被阻塞,除非有另一个线程进行了入队列操作。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值