知乎专栏 |
package cn.netkiller.test; import java.util.concurrent.ExecutionException; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class Test { private final Lock lock = new ReentrantLock(); private int count; public static void main(String[] args) throws ExecutionException, InterruptedException { Test test = new Test(); new Thread(() -> { while (true) { test.add(1); System.out.println(Thread.currentThread().getName() + ": " + test.count); try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } } }, "线程1").start(); new Thread(() -> { while (true) { test.add(1); System.out.println(Thread.currentThread().getName() + ": " + test.count); try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } } }, "线程2").start(); new Thread(() -> { while (true) { test.add(1); System.out.println(Thread.currentThread().getName() + ": " + test.count); try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } } }, "线程3").start(); new Thread(() -> { while (true) { try { Thread.sleep(1000); System.out.println(test.count); } catch (InterruptedException e) { throw new RuntimeException(e); } } }, "线程1").start(); } public void add(int n) { count += n; } }
没有加锁,线程是无序执行的
线程2: 2 线程3: 3 线程1: 1 3 线程2: 4 线程3: 5 线程1: 6 6 线程2: 7 线程1: 8 线程3: 9 线程2: 10 10 线程1: 11 线程3: 12 12 线程1: 14 线程2: 13 线程3: 15 15
package cn.netkiller.test; import java.util.concurrent.ExecutionException; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class Test { private final Lock lock = new ReentrantLock(); private int count; public static void main(String[] args) throws ExecutionException, InterruptedException { Test test = new Test(); new Thread(() -> { while (true) { test.add(1); System.out.println(Thread.currentThread().getName() + ": " + test.count); try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } } }, "线程1").start(); new Thread(() -> { while (true) { test.add(1); System.out.println(Thread.currentThread().getName() + ": " + test.count); try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } } }, "线程2").start(); new Thread(() -> { while (true) { test.add(1); System.out.println(Thread.currentThread().getName() + ": " + test.count); try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } } }, "线程3").start(); new Thread(() -> { while (true) { try { Thread.sleep(1000); System.out.println(test.count); } catch (InterruptedException e) { throw new RuntimeException(e); } } }, "线程1").start(); } public void add(int n) { lock.lock(); try { count += n; } finally { lock.unlock(); } } }
线程3: 3 线程1: 1 线程2: 2 3 线程1: 4 线程3: 5 线程2: 6 6 线程1: 7 线程3: 8 线程2: 9 9 线程1: 10 线程2: 11 线程3: 12 12