マルチスレッドプログラミング学習9(同時ツールクラス).
6229 ワード
CountDownLatch
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");
}
}
CyclicBarrier
public class BankWaterService implements Runnable {
// 4 , run
private CyclicBarrier barrier = new CyclicBarrier(4, this);
// 4 , 4
private Executor executor = Executors.newFixedThreadPool(4);
//
private ConcurrentHashMap 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 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();
}
}
Semaphore
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();
}
}
Exchanger
public class ExchangerTest {
private static final Exchanger 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();
}
}