重入锁ReentrantLock

//多个线程增加1
public class StaticNum {
 
 private static Object obj = new Object();
 private static ReentrantLock lock = new ReentrantLock();
 
 public static void main(String[] args) {
  
  for(int i=0;i<2000;i++) {
   NumThread t = new NumThread("t" + i);
   t.start();
  }
 }

 static class NumThread extends Thread{
  private static int i;
  
  public NumThread(String name) {
   super(name);
  }
  
  public void run() {
   //i++;
   //并发的问题: 1.同步class
   /*
   synchronized(NumThread.class) {
    i++;
   }
   */
   //2.外面的对象同步
//   synchronized(obj) {
//    i++;
//   }
   //3.重入锁 ReentrantLock
   lock.lock();
   try {
    i++;
    System.out.println(this.getName() + "  " + i);
   }finally {
    lock.unlock();
   }
   
  }
  
  
 }
}

猜你喜欢

转载自zw7534313.iteye.com/blog/2419258