在Java应用程序中,你正在处理一个多线程任务。假设有一个共享的计数器 counter,多个线程需要对其进行递增操作。希望保证 counter 的最终结果是线程安全的,同时最大化程序的执行效率。
请使用Java中的多线程机制实现一个线程安全的计数器递增功能。可以选择 synchronized 关键字、ReentrantLock 或 AtomicInteger 来实现线程安全。请提供完整的代码并解释。
在Java应用程序中,你正在处理一个多线程任务。假设有一个共享的计数器 counter,多个线程需要对其进行递增操作。希望保证 counter 的最终结果是线程安全的,同时最大化程序的执行效率。
请使用Java中的多线程机制实现一个线程安全的计数器递增功能。可以选择 synchronized 关键字、ReentrantLock 或 AtomicInteger 来实现线程安全。请提供完整的代码并解释。
关注回答引用自GPT-4o,由博主小ᶻZ࿆编写,若还有疑问可评论或留言:
在Java中,为了保证 counter 在多线程操作下线程安全,可以采用以下三种方式来保证最终结果的正确性,并尽量最大化程序的执行效率:
synchronized 关键字public class Counter {
private int count = 0;
// 使用 synchronized 确保线程安全
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
public class CounterTest {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
Runnable task = () -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
};
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Final counter value: " + counter.getCount());
}
}
increment 方法被 synchronized 关键字保护,确保多个线程不会同时执行该方法,从而保证 count 的更新是线程安全的。
public class CounterWithLock {
private int count = 0;
private final ReentrantLock lock = new ReentrantLock();
public void increment() {
lock.lock(); // 加锁
try {
count++;
} finally {
lock.unlock(); // 确保在任何情况下都释放锁
}
}
public int getCount() {
return count;
}
}
public class CounterTest {
public static void main(String[] args) throws InterruptedException {
CounterWithLock counter = new CounterWithLock();
Runnable task = () -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
};
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Final counter value: " + counter.getCount());
}
}