public class SaleTicket { private int count = 100; public void sale(){ synchronized (this) { if (count>0) { System.out.println(Thread.currentThread().getName()+"卖了第"+count+"张票"); count--; } else { System.out.println(Thread.currentThread().getName()+"--票卖完了!"); } } } public int getCount() { return count; } }
//卖票
public class SaleTicketTest { public static void main(String[] args) { SaleTicket st = new SaleTicket(); ExecutorService executor = Executors.newFixedThreadPool(3); executor.submit(new Runnable() { @Override public void run() { Thread.currentThread().setName("t1"); while (true) { if (st.getCount()>0) { st.sale(); try { Thread.sleep(1); } catch (Exception e) { e.printStackTrace(); } } else { break; } } } }); executor.submit(new Runnable() { @Override public void run() { Thread.currentThread().setName("t2"); while (true) { if (st.getCount()>0) { st.sale(); try { Thread.sleep(1); } catch (Exception e) { e.printStackTrace(); } } else { break; } } } }); executor.submit(new Runnable() { @Override public void run() { Thread.currentThread().setName("t3"); while (true) { if (st.getCount()>0) { st.sale(); try { Thread.sleep(1); } catch (Exception e) { e.printStackTrace(); } } else { break; } } } }); } }