Semaphore/CountDownLatch/CyclicBarrier

CountDownLatch --

CyclicBarrier ++

 

Semaphore -- 資源不足

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoneDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Semaphore semaphore = new Semaphore(3);//3個停車位
		for(int i = 1; i <= 6; i++) {
			//模擬6個汽車
			new Thread(()-> {
				try {
					semaphore.acquire();
					System.out.println(Thread.currentThread().getName() +"\t搶到車位");
					try {
						TimeUnit.SECONDS.sleep(3);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					System.out.println(Thread.currentThread().getName() +"\t離開車位");

				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}finally {
					semaphore.release();
				}
				
			},String.valueOf(i)).start();
		}
	}

}
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class CountDownLatchDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		CountDownLatch countDownLatch = new CountDownLatch(6);
		final Executor executor = Executors.newCachedThreadPool();
	
		
		CyclicBarrier cyclicBarrier = new CyclicBarrier(7,()->{System.out.println(Thread.currentThread().getName());});
		for(int i = 1; i<=6;i++) {
			executor.execute(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					System.out.println(Thread.currentThread().getName()+"\t國,被滅");
					countDownLatch.countDown();
				}
			});
			
			
		}
		
		try {
			countDownLatch.await();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		System.out.println("主線程完成了");
	}

}
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclcBarrierDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		CyclicBarrier cyclicBarrier = new CyclicBarrier(7,()->{System.out.println("成功啦");});

		for(int i = 1; i <= 7; i++) {
			 final int tempInt = i;
			 new Thread(()->{
				 System.out.println(Thread.currentThread().getName()+"\t收集到第第"+tempInt+"龍珠");
				 try {
					cyclicBarrier.await();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (BrokenBarrierException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			 },String.valueOf(i)).start();  
		}
	}

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章