package thread; public class Test02 { //定義初始票數 public static int chepiao = 20; public static void main(String[] args) { Test02 t = new Test02(); //匿名類創建線程 Thread t1 = new Thread() { @Override public void run() { //加同步鎖 synchronized(Test02.class) { //賣完就停止 if(chepiao<=0) { return; } // TODO Auto-generated method stub try { t.jianfa(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } super.run(); } } }; //啟動30個線程 for(int i = 1;i<30;i++) { new Thread(t1).start(); } } //票數-1 public synchronized void jianfa() throws InterruptedException { chepiao--; System.out.println("線程: "+Thread.currentThread().getName()+",搶到1張票,剩余"+chepiao+"張!"); } }
備注:在對變量進行共享線程時,最好使用AtomicInteger 進行自增或遞減操作