您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在Java中,实现并发控制有多种方式,主要包括以下几种:
synchronized
关键字synchronized
关键字可以用来修饰方法或代码块,确保同一时间只有一个线程可以执行被synchronized
修饰的代码。
public class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
ReentrantLock
ReentrantLock
提供了比synchronized
更灵活的锁定机制,可以实现公平锁、非公平锁、可中断锁等。
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Counter {
private int count = 0;
private final Lock lock = new ReentrantLock();
public void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
public int getCount() {
lock.lock();
try {
return count;
} finally {
lock.unlock();
}
}
}
Atomic
类java.util.concurrent.atomic
包中的类提供了原子操作,可以在不使用锁的情况下实现线程安全。
import java.util.concurrent.atomic.AtomicInteger;
public class Counter {
private AtomicInteger count = new AtomicInteger(0);
public void increment() {
count.incrementAndGet();
}
public int getCount() {
return count.get();
}
}
ConcurrentHashMap
ConcurrentHashMap
是线程安全的哈希表实现,适用于高并发场景。
import java.util.concurrent.ConcurrentHashMap;
public class ConcurrentMapExample {
private final ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();
public void put(String key, String value) {
map.put(key, value);
}
public String get(String key) {
return map.get(key);
}
}
BlockingQueue
BlockingQueue
提供了线程安全的队列操作,适用于生产者-消费者模式。
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class ProducerConsumerExample {
private final BlockingQueue<Integer> queue = new LinkedBlockingQueue<>(10);
public void produce(int item) throws InterruptedException {
queue.put(item);
}
public int consume() throws InterruptedException {
return queue.take();
}
}
CountDownLatch
CountDownLatch
允许一个或多个线程等待其他线程完成操作。
import java.util.concurrent.CountDownLatch;
public class CountDownLatchExample {
private final CountDownLatch latch = new CountDownLatch(3);
public void doWork() {
// 模拟工作
latch.countDown();
}
public void waitForCompletion() throws InterruptedException {
latch.await();
}
}
CyclicBarrier
CyclicBarrier
允许一组线程互相等待到达一个屏障点。
import java.util.concurrent.CyclicBarrier;
public class CyclicBarrierExample {
private final CyclicBarrier barrier = new CyclicBarrier(3);
public void doWork() {
try {
barrier.await();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Semaphore
Semaphore
可以控制同时访问某一资源的线程数量。
import java.util.concurrent.Semaphore;
public class SemaphoreExample {
private final Semaphore semaphore = new Semaphore(3);
public void doWork() {
try {
semaphore.acquire();
// 执行工作
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();
}
}
}
选择合适的并发控制机制取决于具体的应用场景和需求。在实际开发中,可能需要结合多种机制来实现高效的并发控制。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。