import java.util.concurrent.locks.*; class Counter { private int count = 0; private Lock lock = new ReentrantLock(); public void increment() { lock.lock(); try { count++; } finally { lock.unlock(); } } public int getCount() { return count; } } class Main { public static void main(String[] args) { Counter counter = new Counter(); Thread thread1 = new Thread(() -> { for (int i = 0; i < 100; i++) { counter.increment(); } }); Thread thread2 = new Thread(() -> { for (int i = 0; i < 100; i++) { counter.increment(); } }); thread1.start(); thread2.start(); try { thread1.join(); thread2.join(); } catch (InterruptedException e) { System.out.println("Threads interrupted."); } System.out.println("Counter value: " + counter.getCount()); } }


上一篇:
下一篇:
切换中文