class tt { public static void main(String[] args) { Runnable st = new SellThread(); new Thread(st).start(); new Thread(st).start(); new Thread(st).start(); new Thread(st).start(); } } class SellThread implements Runnable { int tickets = 100; Object obj = new Object(); public void run() { while (true) { synchronized (obj) { if (tickets > 0) { System.out.println(Thread.currentThread().getName() + "sell tickets" + tickets); tickets--; } else { break; } } try { Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); } } } }
比較適合初學者理解同步,程序中的線程數到底有幾個的問題,我一直對這個沒有一個透徹的理解,實際上Thread xx=new Thread() ;
xx.start() 只是啓動了一個線程,不管run()方法中是不是有無限循環如while(true)。