countDownLatch
作用:用于管制多线程执行协调,即线程先后依赖的问题。如主线程须要期待多个子线程执行实现后继续执行。
示例代码(代码中关键点正文)
public class CountDownTest {
public static void main(String[] args) {
long start = System.currentTimeMillis();
System.out.println("start = " + start);
int num = 100;
LinkedBlockingQueue lbq = new LinkedBlockingQueue();
lbq.stream().count();
final CountDownLatch cdl = new CountDownLatch(num);//参数为线程个数
for (int i = 0; i < num; i++) {
new Thread(() -> {
System.out.println("thread:"+num);
cdl.countDown();//此办法是CountDownLatch的线程数-1
}).start();
}
try {
cdl.await();
}catch (InterruptedException e){
e.printStackTrace();
}
// 通过await()调用,保障以下输入是最开端输入
long end = System.currentTimeMillis();
System.out.println("end = " + end);
System.out.println("use" + (end - start));
}
}
CyclicBarrier
作用:管制多个线程对立工夫执行
示例代码(代码中关键点正文)
public class CyclicBarrierTest {
public static void main(String[] args) {
int num = 5;
CyclicBarrier cyclicBarrier = new CyclicBarrier(num);
for(int i = 0;i<num;i++){
new Thread(() -> {
try {
Thread.sleep(num*1000);
System.out.println(new Date().getTime());
//以下调用将会使改线程参加到栅栏管制中,期待所有栅栏内线程全副初始化实现一起执行
//预期后果为多个线程输入的工夫戳完全一致
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}).start();
}
}
}
Semaphore
作用:管制多个线程同时执行的个数。相似工人和操作台,工人数量大于操作台
示例代码(代码中关键点正文)
public class SemaphoreTest {
public static void main(String[] args) {
int num = 3; //可执行线程数(操作台)
int numThread = 20; //能参加的线程数 (工人)
Semaphore semaphore = new Semaphore(num);
for(int i = 0;i<numThread;i++){
int no = i;
new Thread(()->{
try {
semaphore.acquire(); //工人上工,占用一个操作台
System.out.println("工号:"+ no +"的工人在干活");
Thread.sleep(5000);
System.out.println("工号:"+ no +"的工人上班了");
semaphore.release(); //工人上班,开释操作台
}catch (Exception e){
e.printStackTrace();
}
}).start();
}
}
}
发表回复