Java用多線程實現賣票

    Java小白一個,剛開始學習線程,在這個過程中遇到了一些麻煩,經過2天的努力,終於弄懂了用多線程實現賣票的程序,嗯嗯,記錄一下!
public class TicketImpDemo {
	public static void main(String[] args) {
		Runnable target = new ticket();
		new Thread(target, "A").start();
		new Thread(target, "B").start();
		new Thread(target, "C").start();
	}
}

class ticket implements Runnable {
	static Object o = new Object();
	int num = 5000;

	@Override
	public void run() {
		while (num > 0) {
			synchronized (o) {
				if (num > 0) {
					num--;
					System.out.println(Thread.currentThread().getName() + "賣出了第" + (5000 - num) + "張票");
				}
			}
		}
		System.out.println("票都賣完啦!!!");
	}
}
以上便是我的代碼,希望能夠幫助到大家,同時也歡迎大家批評指正。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章