import java.util.concurrent.CountDownLatch;
public class Main {
public static void main(String[] args) throws InterruptedException {
int count = 5;
CountDownLatch latch = new CountDownLatch(count);
for (int i = 0; i < count; i++) {
new Thread(new Worker(latch)).start();
}
System.out.println("All workers have finished!");
}
}
class Worker implements Runnable {
private CountDownLatch latch;
public Worker(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class Main {
private static final int THREAD_COUNT = 4;
public static void main(String[] args) {
CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT, () ->
System.out.println("All threads have reached the barrier!")
);
for (int i = 0; i < THREAD_COUNT; i++) {
new Thread(new Worker(barrier)).start();
}
}
}
class Worker implements Runnable {
private CyclicBarrier barrier;
public Worker(CyclicBarrier barrier) {
this.barrier = barrier;
}
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
e.printStackTrace();
}
System.out.println("Thread has passed the barrier!");
}
}
import java.util.concurrent.Semaphore;
public class Main {
private static final int THREAD_COUNT = 5;
public static void main(String[] args) {
for (int i = 0; i < THREAD_COUNT; i++) {
new Thread(new Worker(semaphore)).start();
}
}
}
class Worker implements Runnable {
private Semaphore semaphore;
public Worker(Semaphore semaphore) {
this.semaphore = semaphore;
}
@Override
public void run() {
try {
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread is accessing the shared resource...");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}