CountDownLatch
import java.util.concurrent.CountDownLatch;
/**
* 功能:
* N个线程同时开始处理
* 主线程等待N个线程处理完再继续
*
* @auther xh
* @date 10/8/19 4:09 PM
*/
public class CountDownLatchTest {
public static void main(String[] args) throws InterruptedException {
int N = 10;
//开始开关
CountDownLatch startSignal = new CountDownLatch(1);
//N个工作线程
CountDownLatch doneSignal = new CountDownLatch(N);
for (int i = 0; i < N; i++) {
new Thread(new Worker(startSignal, doneSignal)).start();
}
System.out.println(Thread.currentThread().getName() + ": starting...");
startSignal.countDown();
//主线程等待 N 和线程处理完再继续
doneSignal.await();
System.out.println(Thread.currentThread().getName() + ": all finished");
}
}
class Worker implements Runnable {
private CountDownLatch startSignal;
private CountDownLatch doneSignal;
public Worker(CountDownLatch startSignal, CountDownLatch doneSignal) {
this.startSignal = startSignal;
this.doneSignal = doneSignal;
}
public void run() {
try {
//N 个线程同时开始处理
startSignal.await();
doWork();
doneSignal.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void doWork() {
System.out.println(Thread.currentThread().getName() + ": doing work");
}
}
运行结果:
main: starting...
Thread-0: doing work
Thread-1: doing work
Thread-2: doing work
Thread-3: doing work
Thread-4: doing work
Thread-7: doing work
Thread-6: doing work
Thread-8: doing work
Thread-5: doing work
Thread-9: doing work
main: all finished
改造为线程池:
public static void main(String[] args) throws InterruptedException {
int N = 10;
//开始开关
CountDownLatch startSignal = new CountDownLatch(1);
//N个工作线程
CountDownLatch doneSignal = new CountDownLatch(N);
Executor executor = Executors.newCachedThreadPool();
for (int i = 0; i < N; i++) {
//new Thread(new Worker(startSignal, doneSignal)).start();
executor.execute(new Worker(startSignal, doneSignal));
}
System.out.println(Thread.currentThread().getName() + ": starting...");
startSignal.countDown();
//主线程等待 N 和线程处理完再继续
doneSignal.await();
System.out.println(Thread.currentThread().getName() + ": all finished");
//释放资源
((ExecutorService) executor).shutdown();
}
结果:
main: starting...
pool-1-thread-2: doing work
pool-1-thread-1: doing work
pool-1-thread-3: doing work
pool-1-thread-5: doing work
pool-1-thread-4: doing work
pool-1-thread-6: doing work
pool-1-thread-7: doing work
pool-1-thread-8: doing work
pool-1-thread-9: doing work
pool-1-thread-10: doing work
main: all finished
BlockingQueue
public static void main(String[] args) throws InterruptedException {
BlockingQueue<Integer> blockingQueue = new SynchronousQueue<>();
blockingQueue.put(1);
System.out.println(blockingQueue.offer(1));
System.out.println(blockingQueue.offer(2));
System.out.println(blockingQueue.offer(2));
System.out.println(blockingQueue.offer(3));
//System.out.println(blockingQueue.take());
System.out.println(blockingQueue.size());
}