java多线程 关于synchronized wait notify CountDownLatch CyclicBarrier Semaphore


package com.my.JavaThread;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.Semaphore;

public class CountDownTest {
	private static void runDAfterABC() {
		int worker = 3;
		final CountDownLatch countDownLatch = new CountDownLatch(worker);
		new Thread(new Runnable() {
			@Override
			public void run() {
				System.out.println("D is waiting for other three threads");
				try {
					countDownLatch.await();
					System.out.println("All done, D starts working");
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}).start();
		for (char threadName = 'A'; threadName <= 'C'; threadName++) {
			final String tN = String.valueOf(threadName);
			new Thread(new Runnable() {
				@Override
				public void run() {
					System.out.println(tN + "is working");
					try {
						Thread.sleep(100);
					} catch (Exception e) {
						e.printStackTrace();
					}
					System.out.println(tN + "finished");
					countDownLatch.countDown();
				}
			}).start();
		}
	}

	private static void demo3() {
		final Object lock = new Object();
		Thread B = new Thread(new Runnable() {
			@Override
			public void run() {
				synchronized (lock) {
					System.out.println("B 1");
					System.out.println("B 2");
					System.out.println("B 3");
					lock.notify();
				}
			}
		});
		Thread A = new Thread(new Runnable() {
			@Override
			public void run() {
				synchronized (lock) {
					System.out.println("A 1");
					try {
						lock.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("A 2");
					System.out.println("A 3");
				}
			}
		});
		A.start();
		B.start();
		
	}

	private static void runABCWhenAllReady() {
		int runner = 3;
		final CyclicBarrier cyclicBarrier = new CyclicBarrier(runner);
		final Random random = new Random();
		for (char runnerName = 'A'; runnerName <= 'C'; runnerName++) {
			final String rN = String.valueOf(runnerName);
			new Thread(new Runnable() {
				@Override
				public void run() {
					long prepareTime = random.nextInt(10000) + 100;
					System.out.println(rN + "is preparing for time:" + prepareTime);
					try {
						Thread.sleep(prepareTime);
					} catch (Exception e) {
						e.printStackTrace();
					}
					try {
						System.out.println(rN + "is prepared, waiting for others");
						cyclicBarrier.await(); // 当前运动员准备完毕,等待别人准备好
					} catch (InterruptedException e) {
						e.printStackTrace();
					} catch (BrokenBarrierException e) {
						e.printStackTrace();
					}
					System.out.println(rN + "starts running"); // 所有运动员都准备好了,一起开始跑
				}
			}).start();
		}
	}

	
	private static void doTaskWithResultInWorker() {
	    Callable callable = new Callable() {
	        @Override
	        public Integer call() throws Exception {
	            System.out.println("Task starts");
	            Thread.sleep(1000);
	            int result = 0;
	            for (int i=0; i<=101; i++) {
	                result += i;
	            }
	            System.out.println("Task finished and return result");
	            return result;
	        }
	    };
	    FutureTask futureTask = new FutureTask<>(callable);
	    new Thread(futureTask).start();
	    try {
	        System.out.println("Before futureTask.get()");
	        System.out.println("Result:" + futureTask.get());
	        System.out.println("After futureTask.get()");
	    } catch (InterruptedException e) {
	        e.printStackTrace();
	    } catch (ExecutionException e) {
	        e.printStackTrace();
	    }
	}
	
	public static void semaphoretest() {
	    //采用新特性来启动和管理线程——内部使用线程池
	    ExecutorService exec = Executors.newCachedThreadPool();
	    //只允许2个线程同时访问
	    final Semaphore semp = new Semaphore(1);
	    //模拟5个客户端访问
	    Object lock = new Object();
	    
	    for (int index = 0; index < 5; index++){
	    	synchronized (lock) {
	    		final int num = index;
		        Runnable run = new Runnable() {
		            public void run() {
		                try {
		                    //获取许可
		                    semp.acquire();
		                    System.out.println("线程" + 
		                        Thread.currentThread().getName() + "获得许可:"  + num);
		                    //模拟耗时的任务
		                    for (int i = 0; i < 999999; i++) ;
		                    //释放许可
		                    semp.release();
		                    System.out.println("线程" + 
		                        Thread.currentThread().getName() + "释放许可:"  + num);
		                    System.out.println("当前允许进入的任务个数:" +
		                        semp.availablePermits());
		                }catch(InterruptedException e){
		                    e.printStackTrace();
		                }
		            }
		        };
		        exec.execute(run);
		        lock.notify();
	    	}	
	    }
	    //关闭线程池
	    exec.shutdown();
	    }
	
	
	public static void main(String[] args) {
//		CountDownTest.runDAfterABC();
//		System.out.println("-------");
		CountDownTest.demo3();
//		CountDownTest.runABCWhenAllReady();
//		CountDownTest.doTaskWithResultInWorker();
//		CountDownTest.semaphoretest();
	}
}


synchronized wait notify CountDownLatch CyclicBarrier  Semaphore

你可能感兴趣的:(java多线程 关于synchronized wait notify CountDownLatch CyclicBarrier Semaphore)