在Java中实现多线程计数,通常有以下几种方式:
使用AtomicInteger类
使用synchronized关键字或ReentrantLock类来保证线程安全
使用CountDownLatch或CyclicBarrier来协调多个线程
使用AtomicInteger示例
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();
}
}
使用synchronized示例
public class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
使用CountDownLatch示例
订阅专栏 解锁全文
318

被折叠的 条评论
为什么被折叠?



