1. 程式人生 > >各視窗共同賣票 【 Java 多執行緒 】

各視窗共同賣票 【 Java 多執行緒 】

現實中也存在這樣的情況:

模擬一個火車站的售票系統,假如當日從A地發往B地的火車票只有10張,且允許所有視窗賣這10張票,每一個視窗也相當於一個執行緒。

1、Runnable介面實現


public class Main {

	public static void main(String[] args) {

		Test m = new Test();

		Thread w1 = new Thread(m, "window 1");
		Thread w2 = new Thread(m, "window 2");
		Thread w3 = new Thread(m, "window 3");

		w1.start();
		w2.start();
		w3.start();

	}
}

class Test implements Runnable {
	private int n = 10;

	public void run() {
		while (n > 0) {
			System.out.println(n-- + " is saled by " + Thread.currentThread().getName());
		}
	}
}

2、Thread子類實現


public class Main {

	public static void main(String[] args) {

		Ticket t = new Ticket();
		Test w1 = new Test(t,"window 1");
		Test w2 = new Test(t,"window 2");
		Test w3 = new Test(t,"window 3");
		
		w1.start();
		w2.start();
		w3.start();
	}
}

class Ticket {
	int tic = 10;
}
class Test extends Thread{
	private Ticket tick;
	public Test(Ticket tick, String name){
		super(name);
		this.tick = tick;
	}
	public void run(){
		while(tick.tic > 0){
			System.out.println(tick.tic --  + " is saled by " + Thread.currentThread().getName());
		}
	}
}