1. 程式人生 > >實現N個執行緒互相等待完成

實現N個執行緒互相等待完成

1、採用執行緒池的方式,實現有返回值的Callable<V>執行緒介面

package com.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TestThreadCountByExecutor {
	public static void main(String[] args) throws InterruptedException, ExecutionException {
		ExecutorService cxecutorService = Executors.newCachedThreadPool();
		CompletionService<Integer> cs = new ExecutorCompletionService<Integer>(cxecutorService);
		for (int i = 0; i < 4; i++) {
			cs.submit(new Worker(i+1));
		}
		cxecutorService.shutdown();

		int total = 0;
		for (int i = 0; i < 4; i++) {
			total += cs.take().get();
		}
		System.out.println("所有執行緒已完成->>>>>" + total);
	}

	static class Worker implements Callable<Integer> {

		private int type;

		public Worker(int type) {
			this.type = type;
		}

		@Override
		public Integer call() throws Exception {
			if (type == 1) {
				System.out.println("統計C完畢");
				return 1;
			} else if (type == 2) {
				Thread.sleep(10000);
				System.out.println("統計D完畢");
				return 2;
			} else if (type == 3) {
				Thread.sleep(5000);
				System.out.println("統計E完畢");
				return 3;
			} else if (type == 4) {
				System.out.println("統計F完畢");
				return 4;
			} else {
				System.out.println("邏輯出錯");
				return null;
			}
		}
	}
}

2、採用java.util.concurrent包下的CountDownLatch類來實現

package com.thread;

import java.util.concurrent.CountDownLatch;

public class TestCountFirthThread {

	public static void main(String[] args) {
		try {
			CountDownLatch latch = new CountDownLatch(2);
			Thread work1 = new StatisticalThread(latch, 2000, "work1");
			Thread work2 = new StatisticalThread(latch, 5000, "work2");
			work1.start();
			work2.start();
			latch.await();
			System.out.println("finsh");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

	}

	static class StatisticalThread extends Thread {
		CountDownLatch latch;
		int waitTime;
		String threadName;

		public StatisticalThread(CountDownLatch latch, int waitTime, String threadName) {
			super();
			this.latch = latch;
			this.waitTime = waitTime;
			this.threadName = threadName;
		}

		@Override
		public void run() {
			try {
				System.out.println("statisticalThread " + threadName + " start");
				Thread.sleep(waitTime);
				System.out.println("statisticalThread " + threadName + " finsh");
				latch.countDown();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}