一個簡單多線程購票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 進行自增或遞減操作

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM