import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Semaphore;
public class ConcurrentExample {
private static ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
private static ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<>();
private static Semaphore semaphore = new Semaphore(3);
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
new Thread(() -> {
map.put(Thread.currentThread().getName(), 1);
}).start();
}
for (int i = 0; i < 3; i++) {
new Thread(() -> {
Integer value = map.get(Thread.currentThread().getName());
System.out.println(value);
}).start();
}
for (int i = 0; i < 4; i++) {
new Thread(() -> {
queue.offer(Thread.currentThread().getName());
}).start();
}
for (int i = 0; i < 2; i++) {
new Thread(() -> {
String value = queue.poll();
System.out.println(value);
}).start();
}
for (int i = 0; i < 6; i++) {
new Thread(() -> {
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + " acquired the semaphore");
Thread.sleep(1000);
semaphore.release();
System.out.println(Thread.currentThread().getName() + " released the semaphore");
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
}
}