主方法ide
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:this
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:spa
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()方法加入了鎖,其餘線程方法時若是當前鎖沒有釋放進去等待狀態等線程釋放鎖後進入鎖的爭奪。每次只容許一個線程訪問。code
ReentrantLock 利用lock.lock()得到鎖,lock.unlock()釋放鎖,實現與synchronized一樣的效果。blog