一个简单多线程购票Demo
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 进行自增或递减操作