多執行緒賣火車票簡單例子

rodertW發表於2019-01-30
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

public class JavaTest {

	public static void main(String[] args) {
		SaleTicket st = new SaleTicket();
		Thread t1 = new Thread(st, "一號視窗");
		Thread t2 = new Thread(st, "二號視窗");
		Thread t3 = new Thread(st, "三號視窗");
		Thread t4 = new Thread(st, "四號視窗");
		t1.start();
		t2.start();
		t3.start();
		t4.start();
	}
}

class SaleTicket extends Thread {// sale英 [seɪl] n.拍賣;賣,出賣;
	private int tickets = 100;

	@Override
	public void run() {
		while (tickets > 0) {
			sale();
		}
	}

	private synchronized void sale() {// synchronized 同步。
		if (tickets > 0) {
			System.out.println(Thread.currentThread().getName() + "賣出了第"
					+ (100 - tickets + 1) + "張票");
			tickets--;

			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}// 假設購票過程需要500毫秒。

		}
	}
}

 

相關文章