天天看點

java 買票賣票

package example_SellTicket;

/*

 * //修飾方法 預設鎖定目前對象 不讓别人賣了

 * 有問題

 */

class A2 implements Runnable {

 public static int ticket = 100;

 String str = "我來是實作同步";



 public synchronized void run() {//修飾方法 預設鎖定目前對象 不讓别人賣了



 while (true) {
 

 if (ticket > 0) {

 System.out.println(Thread.currentThread().getName() + "正在買出第" + ticket + "張票");

 ticket--;

 } else {

 break;

 }
 

 }

 }

}



public class TicketTest4 {



 public static void main(String[] args) {

 A2 a = new A2();

 Thread t1 = new Thread(a);

 t1.start();

 Thread t2 = new Thread(a);

 t2.start();

 }

}



/*

 * synchronized (mutex) { API給你一個方法 說此方法是線程同步的,其實是說 此方法被synchronized修飾 多線程調用時

 * 達到互斥

 * 

 * }

 */      

繼續閱讀