Java concurrent包下线程池的三个特性【实例】
特性1:CountDownLatch
A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.
private static void testCountDownLatch() throws InterruptedException {
int count = 100;
//等待主线程
final CountDownLatch start = new CountDownLatch(1);
final CountDownLatch end = new CountDownLatch(count);
List<Thread> threads = new ArrayList<Thread>();
for (int i = 1; i <= 100; i++)
{
threads.add(new Thread(new Runnable()
{
public void run()
{
try {
start.await();
System.out.println(Thread.currentThread().getName() + " do something done");
} catch (InterruptedException e)
{
e.printStackTrace();
}
finally
{
end.countDown();
}
}
}, "test-thread-" + i));
}
for (Thread th : threads) {
th.start();
}
//开始所有线程
start.countDown();
//等待所有线程执行完毕
end.await();
System.out.println("main thread over!");
}
特性2:CyclicBarrier
线程栅栏 可重入
private static void testCy() {
int count = 10;
final CyclicBarrier cyclicBarrier = new CyclicBarrier(count, new Runnable()
{
public void run()
{
//每次所有线程到达栅栏后执行
System.out.println(" last thread over!");
}
});
List<Thread> threads = new ArrayList<Thread>();
for (int i = 1; i <= count; i++)
{
threads.add(new Thread(new Runnable()
{
public void run()
{
try {
TimeUnit.SECONDS.sleep(1);
System.out.println(Thread.currentThread().getName() + " do something once!");
cyclicBarrier.await();
TimeUnit.SECONDS.sleep(1);
System.out.println(Thread.currentThread().getName() + " do something twice!");
cyclicBarrier.await();
TimeUnit.SECONDS.sleep(1);
System.out.println(Thread.currentThread().getName() + " do something third times!");
cyclicBarrier.await();
} catch (InterruptedException e)
{
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}
}, "test-thread-" + i));
}
for (Thread th : threads) {
th.start();
}
}
特性3:信号
private static void testSemaphore() {
int count = 10;
//同时允许连个线程执行
final Semaphore semaphore = new Semaphore(2);
List<Thread> threads = new ArrayList<Thread>();
for (int i = 1; i <= count; i++)
{
threads.add(new Thread(new Runnable()
{
public void run()
{
try
{
//获取信号
semaphore.acquire();
TimeUnit.SECONDS.sleep(1);
System.out.println(Thread.currentThread().getName() + " do something done!");
} catch (InterruptedException e)
{
e.printStackTrace();
}
finally
{
semaphore.release();
}
}
}, "test-thread-" + i));
}
for (Thread th : threads) {
th.start();
}
}
建议配合线程池使用。
谢谢分享,我重新编辑了一下格式。😙