import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class Counter { private int count = 0; private Lock lock = new ReentrantLock(); public void increment() { lock.lock(); try { count++; } finally { lock.unlock(); } } public int getCount() { return count; } } import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class CustomQueue<T> { private Object[] queue; private int size; private int head; private int tail; private Lock lock = new ReentrantLock(); private Condition notEmpty = lock.newCondition(); private Condition notFull = lock.newCondition(); public CustomQueue(int capacity) { queue = new Object[capacity]; size = 0; head = 0; tail = 0; } public void enqueue(T value) throws InterruptedException { lock.lock(); try { while (size == queue.length) { notFull.await(); } queue[tail] = value; tail = (tail + 1) % queue.length; size++; notEmpty.signalAll(); } finally { lock.unlock(); } } public T dequeue() throws InterruptedException { lock.lock(); try { while (size == 0) { notEmpty.await(); } T value = (T) queue[head]; head = (head + 1) % queue.length; size--; notFull.signalAll(); return value; } finally { lock.unlock(); } } } import java.util.concurrent.ConcurrentHashMap; public class ThreadSafeMap { private ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>(); public void put(String key, int value) { map.put(key, value); } public int get(String key) { return map.get(key); } } import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ThreadPoolDemo { private ExecutorService executor = Executors.newFixedThreadPool(10); public void executeTask(Runnable task) { executor.execute(task); } public void shutdown() { executor.shutdown(); } }


上一篇:
下一篇:
切换中文