【Java】CountDownLatch和Semaphore使用场景
CountDownLatch
package com.keytech.task;import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
class TaskApplicationTests {
//目标:炒菜
//1.洗菜 5秒
//2.买盐 3秒
public static void main(String[] args) throws InterruptedException {
Executor executor=Executors.newFixedThreadPool(2);
CountDownLatch countDownLatch=new CountDownLatch(2);
long now = System.currentTimeMillis();
//洗菜5秒
executor.execute(()->{
try{
Thread.sleep(5000);
}catch (Exception e){
e.printStackTrace();
}finally {
if(countDownLatch!=null){
countDownLatch.countDown();
}
}
});
//买盐3秒
executor.execute(()->{
try{
Thread.sleep(3000);
}catch (Exception e){
e.printStackTrace();
}finally {
if(countDownLatch!=null){
countDownLatch.countDown();
}
}
});
countDownLatch.await();
System.out.println("可以炒菜了"+(System.currentTimeMillis()-now));
}
}
//可以炒菜了5082
Semaphore
package com.keytech.task;import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
/**
* @className: SemaphoreTest
* @description: TODO 类描述
* @author: mac
* @date: 2020/12/26
**/
public class SemaphoreTest {
public static void main(String[] args) {
ExecutorService executor=Executors.newFixedThreadPool(40);
Semaphore semaphore=new Semaphore(10);
for (int i = 0; i < 40; i++) {
executor.execute(()->{
try {
semaphore.acquire();
System.out.println("处理数据中......");
Thread.sleep(3000);
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
executor.shutdown();
}
}
以上是 【Java】CountDownLatch和Semaphore使用场景 的全部内容, 来源链接: utcz.com/a/86916.html