关于这三个工具类,个人的一点理解:
CountDownLantch,一般应用于将多线程执行完之后再执行main线程,起到一个将上下文由异步转化为同步的效果;
CycliBarrier,是将所有异步线程执行完之后,再由这其中的一个线程执行最后一个任务;
semaphore,起一个限流的作用,比如有10个线程同时访问某个资源,可以设置成每两个线程执行完释放锁后再由其他线程抢这两个锁;
public class TestCountDown {
private static CountDownLatch cd = new CountDownLatch(10);
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + "飘过...");
cd.countDown();
}, String.valueOf(i)).start();
}
try {
cd.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "最后执行");
}
}
public class TestCyclicBarrier {
public static void main(String[] args) {
CyclicBarrier cb = new CyclicBarrier(10, new Thread(() -> {
System.out.println(Thread.currentThread().getName() + "\t 最后执行");
}));
for (int i = 1; i <= 10; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + "飘过...");
try {
cb.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}, String.valueOf(i)).start();
}
}
}
public class TestSemaPhore {
public static void main(String[] args) {
Semaphore sp = new Semaphore(2);
//有10个线程进来,每次只允许2个线程同时工作
for (int i = 1; i <= 10; i++) {
new Thread(() -> {
try {
sp.acquire();
System.out.println(Thread.currentThread().getName() + "\t come in");
Thread.sleep(2000);
System.out.println(Thread.currentThread().getName() + "\t come out");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
sp.release();
}
}, String.valueOf(i)).start();
}
}
}