在Java中,多線程并發控制可以通過以下幾種方式實現:
public class SynchronizedExample {
private int counter = 0;
public synchronized void increment() {
counter++;
}
public synchronized int getCounter() {
return counter;
}
}
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class LockExample {
private int counter = 0;
private final Lock lock = new ReentrantLock();
public void increment() {
lock.lock();
try {
counter++;
} finally {
lock.unlock();
}
}
public int getCounter() {
return counter;
}
}
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicExample {
private AtomicInteger counter = new AtomicInteger(0);
public void increment() {
counter.incrementAndGet();
}
public int getCounter() {
return counter.get();
}
}
import java.util.concurrent.ConcurrentHashMap;
public class ConcurrentHashMapExample {
private ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
public void put(String key, Integer value) {
map.put(key, value);
}
public Integer get(String key) {
return map.get(key);
}
}
public class VolatileExample {
private volatile int counter = 0;
public void increment() {
counter++;
}
public int getCounter() {
return counter;
}
}
public class ThreadLocalExample {
private ThreadLocal<Integer> threadLocalCounter = new ThreadLocal<>();
public void setCounter(int value) {
threadLocalCounter.set(value);
}
public int getCounter() {
return threadLocalCounter.get();
}
}
根據具體場景和需求,可以選擇合適的并發控制方式來實現多線程編程。