ReentrantLock:
1 /** 2 * ReentrantLock测试逻辑类 3 */ 4 public class MyService { 5 private Lock lock = new ReentrantLock();//获取锁对象 6 7 public void methodA() { 8 try { 9 lock.lock(); 10 System.out.println("methodA:----begin" + Thread.currentThread().getName() + "----" + System.currentTimeMillis()); 11 Thread.sleep(2000); 12 System.out.println("methodA:----end" + Thread.currentThread().getName() + "----" + System.currentTimeMillis()); 13 } catch (InterruptedException e) { 14 e.printStackTrace(); 15 }finally { 16 lock.unlock(); 17 } 18 } 19 20 public void methodB() { 21 try { 22 lock.lock(); 23 System.out.println("methodB:----begin" + Thread.currentThread().getName() + "----" + System.currentTimeMillis()); 24 Thread.sleep(2000); 25 System.out.println("methodB:----end" + Thread.currentThread().getName() + "----" + System.currentTimeMillis()); 26 } catch (InterruptedException e) { 27 e.printStackTrace(); 28 }finally { 29 lock.unlock(); 30 } 31 } 32 }
1 /** 2 * 线程A 3 */ 4 public class ThreadA extends Thread { 5 6 private MyService service; 7 8 public ThreadA(MyService service) { 9 this.service = service; 10 } 11 12 @Override 13 public void run() { 14 service.methodA(); 15 } 16 }
1 /** 2 * 线程AA 3 */ 4 public class ThreadAA extends Thread { 5 6 private MyService service; 7 8 public ThreadAA(MyService service) { 9 this.service = service; 10 } 11 12 @Override 13 public void run() { 14 service.methodA(); 15 } 16 }
1 /** 2 * 线程B 3 */ 4 public class ThreadB extends Thread { 5 6 private MyService service; 7 8 public ThreadB(MyService service) { 9 this.service = service; 10 } 11 12 @Override 13 public void run() { 14 service.methodB(); 15 } 16 }
1 /** 2 * 线程BB 3 */ 4 public class ThreadBB extends Thread { 5 6 private MyService service; 7 8 public ThreadBB(MyService service) { 9 this.service = service; 10 } 11 12 @Override 13 public void run() { 14 service.methodB(); 15 } 16 }
1 /** 2 * 测试类 3 */ 4 public class Run { 5 6 public static void main(String[] args) { 7 MyService service = new MyService(); 8 9 ThreadA a = new ThreadA(service); 10 a.setName("A"); 11 a.start(); 12 ThreadAA aa = new ThreadAA(service); 13 aa.setName("AA"); 14 aa.start(); 15 16 ThreadB b = new ThreadB(service); 17 b.setName("B"); 18 b.start(); 19 ThreadBB bb = new ThreadBB(service); 20 bb.setName("BB"); 21 bb.start(); 22 } 23 }
运行结果如下: