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(); } }
建立票池
package cn.ljs.FristSync; public class SalerDemo01 extends Thread{ private String name; private TicketsPool pool; public SalerDemo01(String name, TicketsPool pool){ this.name = name; this.pool = pool; } public void run(){ while (true){ int num = pool.getTickets(); if (num != 0) { System.out.println(name+"卖了"+num); }else { return; } } } public static void main(String[] args) { TicketsPool pool = new TicketsPool(); SalerDemo01 saler1 = new SalerDemo01("01", pool); SalerDemo01 saler2 = new SalerDemo01("02", pool); SalerDemo01 saler3 = new SalerDemo01("03", pool); saler1.start(); saler2.start(); saler3.start(); } } class TicketsPool{ private int num = 100; public int getTickets(){ synchronized (this) { int tmp = num; num--; return tmp > 0 ? tmp:0; } } }