标签:shutdown inter read val 场景 get res 线程 获得
public class CountDownLatchTest {
private static final CountDownLatch DOWN_LATCH = new CountDownLatch(2);
public static void main(String[] args) throws InterruptedException {
new Thread(() -> {
System.out.println(1);
DOWN_LATCH.countDown();
System.out.println(2);
DOWN_LATCH.countDown();
}).start();
DOWN_LATCH.await();
System.out.println("3");
}
}
public class BankWaterService implements Runnable {
// 创建4个屏障,处理完之后执行当前类的run方法
private CyclicBarrier barrier = new CyclicBarrier(4, this);
// 假设有4个计算任务,所以只启动4个线程
private Executor executor = Executors.newFixedThreadPool(4);
// 保存每个任务的计算结果
private ConcurrentHashMap<String, Integer> sheetBankWaterCount = new ConcurrentHashMap<>();
private AtomicInteger atomicInteger = new AtomicInteger(1);
private void count() {
for (int i = 0; i < 4; i++) {
Thread thread = new Thread(() -> {
// 当前任务的计算结果,计算过程忽略
sheetBankWaterCount.put(Thread.currentThread().getName(), 1);
// 计算完成,插入一个屏障
try {
barrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}, "线程" + atomicInteger.getAndIncrement());
executor.execute(thread);
}
}
@Override
public void run() {
int result = 0;
// 汇总每个任务计算出的结果
for (Map.Entry<String, Integer> sheet : sheetBankWaterCount.entrySet()) {
result += sheet.getValue();
}
//将结果输出
sheetBankWaterCount.put("result", result);
System.out.println(result);
}
public static void main(String[] args) {
BankWaterService bankWaterCount = new BankWaterService();
bankWaterCount.count();
}
}
public class SemaphoreTest {
private static final int THREAD_COUNT = 30;
private static ExecutorService EXECUTOR = Executors.newFixedThreadPool(THREAD_COUNT);
private static Semaphore SEMAPHORE = new Semaphore(10);
private static AtomicInteger ATOMICINTEGER = new AtomicInteger(1);
public static void main(String[] args) {
for (int i = 0; i < THREAD_COUNT; i++) {
EXECUTOR.execute(() -> {
try {
SEMAPHORE.acquire();
System.out.println("save data" + ATOMICINTEGER.getAndIncrement());
SEMAPHORE.release();
} catch (InterruptedException e) {
}
});
}
EXECUTOR.shutdown();
}
}
public class ExchangerTest {
private static final Exchanger<String> exchange = new Exchanger<>();
private static ExecutorService threadPool = Executors.newFixedThreadPool(2);
public static void main(String[] args) {
threadPool.execute(() -> {
try {
String result = exchange.exchange("数据A");
System.out.println("A的exchange结果:" + result);
} catch (InterruptedException e) {
}
});
threadPool.execute(() -> {
try {
String result = exchange.exchange("数据B");
System.out.println("B的exchange结果:" + result);
} catch (InterruptedException e) {
}
});
threadPool.shutdown();
}
}
标签:shutdown inter read val 场景 get res 线程 获得
原文地址:https://www.cnblogs.com/jmcui/p/11511413.html