java多线程并发awaitTermination,CountDownLatch 的使用

java 并发之awaitTermination,CountDownLatch 的使用

join会然线程执行完后执行下一步

public static void main(String args[]) throws InterruptedException, ExecutionException {
Thread d = new Thread(new Task3());
		d.start();
		d.join();
		System.out.println("---------");
}		
class Task2 implements Callable {
	@Override
	public Integer call() throws Exception {
		System.out.println("---------Task2");
		Thread.sleep(1000);
		return 2;
	}
}
	class Task3 implements Runnable {

	public Task3() {
	}
	@Override
	public void run() {
		System.out.println("---------Task1");
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
	class Task1 implements Runnable {
	CountDownLatch count;
	public Task1(CountDownLatch count) {
		// TODO Auto-generated constructor stub
		this.count = count;
	}
	@Override
	public void run() {
		System.out.println("---------Task1");
		count.countDown();
	}
}

如果需要执行完全部线程再执行下一步调用使用awaitTermination

	ExecutorService executor = Executors.newCachedThreadPool();
		for (int i = 0; i < 100; i++) {
			executor.submit(new Task3());
		}
		executor.shutdown(); // 
		System.out.println("开始等待");
        boolean b = executor.awaitTermination(3, TimeUnit.SECONDS);
        System.out.println("等待完毕");
        if(b){
            System.out.println("分线程已经结束");
        }
        System.out.println(Thread.currentThread().getName());//

使用线程池Callable返回执行结果

executor.awaitTermination(3, TimeUnit.HOURS); // 使用线程池Callable返回执行结果
		for (int i = 0; i < 100; i++) {
			Future submit = executor.submit(new Task2());
			System.out.println(submit.get());
		}

在很多高并发的环境下,有可能Callable和FutureTask会创建多次。FutureTask能够在高并发环境下确保任务只执行一次。

		for (int i = 0; i < 100; i++) {
			FutureTask futureTask = new FutureTask<>(new Task2());
			executor.submit(futureTask);
			System.out.println(futureTask.get());
		}
		executor.shutdown();
CountDownLatch count = new CountDownLatch(5);
		for (int i = 1; i <= 5; i++) {
			Thread my = new Thread(new Task1(count));
			my.start();
		}

		try {
			count.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("---------");

你可能感兴趣的:(java,多线程,thread,并发编程,java)