Ζℤ 2024-09-21 20:07 采纳率: 87.5%
浏览 4
已结题

保证 counter 的最终结果是线程安全的,同时最大化程序的执行效率。

在Java应用程序中,你正在处理一个多线程任务。假设有一个共享的计数器 counter,多个线程需要对其进行递增操作。希望保证 counter 的最终结果是线程安全的,同时最大化程序的执行效率。

请使用Java中的多线程机制实现一个线程安全的计数器递增功能。可以选择 synchronized 关键字、ReentrantLock 或 AtomicInteger 来实现线程安全。请提供完整的代码并解释。

  • 写回答

2条回答 默认 最新

  • 小ᶻ☡꙳ᵃⁱᵍᶜ꙳ 优质创作者: 人工智能技术领域 2024-09-22 20:32
    关注

    回答引用自GPT-4o,由博主小ᶻZ࿆编写,若还有疑问可评论或留言:

    在Java中,为了保证 counter 在多线程操作下线程安全,可以采用以下三种方式来保证最终结果的正确性,并尽量最大化程序的执行效率:

    1. 使用 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 的更新是线程安全的。

    1. 使用 ReentrantLock
      ```JAVA
      import java.util.concurrent.locks.ReentrantLock;

    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());
    }
    

    }

    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 10月2日
  • 已采纳回答 9月24日
  • 创建了问题 9月21日