ReentrantLock线程锁
1 public static void main(String[] args) { 2 Test tl = new Test(); 3 Thread th = new Thread(tl); 4 Thread th1 = new Thread(tl); 5 th.start(); 6 th1.start(); 7 }
测试线程:
1 class Test implements Runnable { 2 static Lock lock = new ReentrantLock(); 3 @Override 4 public void run() { 5 lock.lock();//上锁 6 Thread t = Thread.currentThread(); 7 8 for(int i=0;i<50;i++) { 9 try { 10 t.sleep(1000); 11 } catch (InterruptedException e) { 12 // TODO Auto-generated catch block 13 e.printStackTrace(); 14 } 15 System.out.print(t.getName()+" :"); 16 System.out.println("-"); 17 } 18 lock.unlock();//解锁 19 } 20 }