在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();
}
}
根据具体场景和需求,可以选择合适的并发控制方式来实现多线程编程。