synchronized与ReentrantLock实现共享资源的消费
主方法
public class synchronizedTest { public static void main(String[] args) { long startTime = System.currentTimeMillis(); TicketSystem ticketSystem=new TicketSystem(); Thread t1=new Thread(ticketSystem); Thread t2=new Thread(ticketSystem); Thread t3=new Thread(ticketSystem); Thread t4=new Thread(ticketSystem); t1.setName("1号售票点"); t2.setName("2号售票点"); t3.setName("3号售票点"); t4.setName("4号售票点"); t1.start(); t2.start(); t3.start(); t4.start(); while (true) { if(ticketSystem.getTicKetNumber()<=0){ long endTime = System.currentTimeMillis(); float seconds = (endTime - startTime) / 1000F; System.out.println(Float.toString(seconds) + " seconds."); break; } } } }
synchronized线程方法1:
public class TicketSystem implements Runnable { private static volatile int ticketNumber = 900; public int getTicKetNumber() { return this.ticketNumber; } @Override public synchronized void run() { while (true) { if (ticketNumber <= 0) { break; } else { System.out.println(Thread.currentThread().getName() + "卖了最后第" + ticketNumber + "票"); ticketNumber--; } } } }
ReentrantLock线程方法2:
public class TicketSystem implements Runnable { private static volatile int ticketNumber = 900; private ReentrantLock lock = new ReentrantLock(); public int getTicKetNumber() { return this.ticketNumber; } @Override public void run() { while (true) { lock.lock(); if (ticketNumber <= 0) { break; } else { System.out.println(Thread.currentThread().getName() + "卖了最后第" + ticketNumber + "票"); ticketNumber--; } lock.unlock(); } } }
总结:
synchronized在这里将run()方法加入了锁,其他线程方法时如果当前锁没有释放进去等待状态等线程释放锁后进入锁的争夺。每次只允许一个线程访问。
ReentrantLock 利用lock.lock()获得锁,lock.unlock()释放锁,实现与synchronized同样的效果。