CountDownLatch:线程执行完毕之后唤醒主线程往下运行
CyclicBarrier:就像栅栏一样,等所有人迈过,又回到同一起跑线之后继续走自己的路
Semahore:信号量,控制资源占用
sychronize:同步控制关键字,容易发生死锁,在低竞争的时候性能比较好,用法简单
lock:可以配置超时时间,适用于高竞争环境,一定要注意释放锁
package test;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Semaphore;
/**
* Created by wzm on 2016/9/21.
*/
public class CyclicBarrierTest {
public static void main(String[] args) {
int n = 5;
CyclicBarrier barrier = new CyclicBarrier(n);
CountDownLatch latch = new CountDownLatch(n);
Semaphore semaphore = new Semaphore(n);
int workerNum = 10;
/*for (int i=0; i<n; i++) {
new Thread(new Worker(barrier, latch)).start();
}*/
for (int i=0; i<10; i++) {
new Machine(semaphore, i).start();
}
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("主线程执行");
}
static class Worker implements Runnable {
private CyclicBarrier barrier;
private CountDownLatch latch;
public Worker(CyclicBarrier barrier, CountDownLatch latch) {
this.barrier = barrier;
this.latch = latch;
}
public void run() {
System.out.println(Thread.currentThread().getName() + "正在执行");
try {
barrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "执行完毕");
latch.countDown();
}
}
static class Machine extends Thread {
Semaphore semaphore;
int i;
public Machine(Semaphore semaphore, int i) {
this.semaphore = semaphore;
this.i = i;
}
@Override
public void run() {
try {
semaphore.acquire();
System.out.println("工人"+i+"占用到机器开始生产");
Thread.sleep(100);
semaphore.release();
System.out.println("工人"+i+"生产完成,释放机器");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}