synchronized 同步代碼塊,售票問題
阿新 • • 發佈:2018-12-02
ets extend true tick 同步代碼塊 public 同步 syn args
package cn.ljs.FristSync; public class SalerDemo extends Thread { static int tickets = 1000; String name; static Object lock = new Object(); public SalerDemo(String name) { this.name = name; } public void run(){ while(true){ synchronized (lock) { if (tickets < 1) { return ; } System.out.println(name + ": " + tickets); tickets--; } } } public static void main(String[] args) { Thread t1 = new SalerDemo("saler1"); Thread t2 = new SalerDemo("saler2"); Thread t3 = new SalerDemo("saler3"); t1.start(); t2.start(); t3.start(); } }
synchronized 同步代碼塊,售票問題