java并发包&线程池原理分析&锁的深度化

java并发包&线程池原理分析&锁的深度化

将不安全的map集合转成安全集合

HashMap HashMap = new HashMap<>();
Collections.synchronizedMap(HashMap);

concurrentHasMap 开发推荐使用这种map———线程安全且效率高

java并发包&线程池原理分析&锁的深度化

CountDownLatch

java并发包&线程池原理分析&锁的深度化

public class Test002 {

	public static void main(String[] args) throws InterruptedException {
	   CountDownLatch countDownLatch = new CountDownLatch(1);
		new Thread(new Runnable() {
			public void run() {
				System.out.println("我是子线程开始执行任务......");
				try {
					//子线程正在处理事情
					Thread.sleep(10);
				} catch (Exception e) {
					// TODO: handle exception
				}
				countDownLatch.countDown();//每次减1
				System.out.println("我是子线程开始执行任务......");
			}
		}).start();;
		new Thread(new Runnable() {
			public void run() {
				System.out.println("我是子线程开始执行任务......");
				try {
					//子线程正在处理事情
					Thread.sleep(10);
				} catch (Exception e) {
					// TODO: handle exception
				}
				countDownLatch.countDown();//每次减1
				System.out.println("我是子线程开始执行任务......");
			}
		}).start();
		countDownLatch.await();//如果不为0的时候,一直等待
		System.out.println("主线程开始执行任务");
		for (int i = 0; i < 10; i++) {
			System.out.println("main i:"+i);
		}
	}

}

CyclicBarrier

java并发包&线程池原理分析&锁的深度化

class Writer extends Thread {
	CyclicBarrier cyclicBarrier;
	public Writer(CyclicBarrier cyclicBarrier){
		this.cyclicBarrier=cyclicBarrier;
	}
	@Override
	public void run() {
		System.out.println(Thread.currentThread().getName() + "开始写入数据...");
		try {
			// 模拟耗时时间
			Thread.sleep(30);
			
			// 执行并行执行成功
			System.out.println(Thread.currentThread().getName() + "写入数据成功...");
			cyclicBarrier.await();
			System.out.println(Thread.currentThread().getName() + "所有数据执行完毕...");
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

}

public class Test003 {

	public static void main(String[] args) {
		CyclicBarrier cyclicBarrier=	new CyclicBarrier(5);
		for (int i = 0; i < 5; i++) {
			new Writer(cyclicBarrier).start();
		}
	}

}

java并发包&线程池原理分析&锁的深度化

class Parent extends  Thread {
	Semaphore wc;
	String name;

	public Parent(Semaphore wc, String name) {
		this.wc = wc;
		this.name = name;
	}

	@Override
	public void run() {
		// 获取到资源,减去1
		int availablePermits = wc.availablePermits();
		if (availablePermits > 0) {
			System.out.println(name + "天主我也,我有茅坑啦!!");
		} else {
			System.out.println(name + "怎么没有茅坑了.....");
		}
		try {
			wc.acquire();
			System.out.println(name+"终于能上厕所了,爽!!!");
			
			Thread.sleep(new Random().nextInt(1000)); // 模拟上厕所时间。
			System.out.println(name+"厕所终于上完啦!");
			
		} catch (InterruptedException e) {
		}finally {
			//释放茅坑
			wc.release();
		}
	}
}

public class Test004 {
	public static void main(String[] args) throws InterruptedException {
		Semaphore semaphore = new Semaphore(3);
		for (int i = 1; i <=10; i++) {
			  new Parent(semaphore,"第"+i+"个"+",").start();
		}
	}
}