先上图

测试代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
   | public class Test {     static int m = 0;
      public static void main(String[] args) throws InterruptedException {
          Thread[] threads = new Thread[10];
          for (int i = 0; i < threads.length; i++){             threads[i] = new Thread(new Runnable() {                 public void run() {                     for (int i = 0; i < 10000; i++) m++;                 }             });         }
          for (Thread t :threads) t.start();         for (Thread t :threads) t.join();
          System.out.println(m);     }
  }
  | 
 
很经典的一个代码,就开辟10个线程对m进行++操作,由于m++不具有原子性,不加锁的话大概率得到的结果小于10000。现在用它来判断这个锁加成功了没有。【运行结果为10000证明是我们想要的锁效果】。
- 现在用这三个方法加锁:锁非静态变量、锁this、锁非静态方法。
 
运行后可以看到结果都小于10000 ,证明这个只对对象/方法所在线程生效。
- 同理,用静态方法、静态变量和当前类(Test.class)加锁的话
 
会发现结果是恒为10000的,即在多个线程内是共享生效的。
证明的首图的正确性。
另一个例子请看:https://www.cnblogs.com/fengzheng/p/12066239.html