import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class Counter { private int count; private Lock lock; public Counter() { count = 0; lock = new ReentrantLock(); } public void increment() { lock.lock(); try { count++; } finally { lock.unlock(); } } public int getCount() { return count; } } public class Main { public static void main(String[] args) throws InterruptedException { Counter counter = new Counter(); Thread t1 = new Thread(() -> { for (int i = 0; i < 100000; i++) { counter.increment(); } }); Thread t2 = new Thread(() -> { for (int i = 0; i < 100000; i++) { counter.increment(); } }); t1.start(); t2.start(); t1.join(); t2.join(); } }


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