1. 程式人生 > 其它 >使用Java多執行緒模擬一個簡單的賣票系統

使用Java多執行緒模擬一個簡單的賣票系統

技術標籤:Javajava多執行緒

使用Java多執行緒模擬一個簡單的賣票系統**
MyThread頁
public class MyThread implements Runnable {
private int p=10;

@Override
public void run() {
	//獲取當前執行的執行緒
	Thread ct = Thread.currentThread();
	//獲取當前執行緒的名字;
	String name = ct.getName();
	Random ra=new Random();
	//幹活
	while(p>0) {
		//讓當前執行緒隨機休息幾秒
		try {
			int n=ra.nextInt(6)*1000;
			ct.sleep(n);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		System.out.println(name+"在賣第"+p+"張票");
		p--;
	}
	
}

}

Test測試頁
public class Test {
public static void main(String[] args) {
MyThread mt=new MyThread();//例項化Runnable類的物件
//通過該物件建立4個執行緒
Thread th1=new Thread(mt,“小明”);
Thread th2=new Thread(mt,“小紅”);
Thread th3=new Thread(mt,“小蘭”);
Thread th4=new Thread(mt,“小強”);

	//讓執行緒啟動
	th1.start();
	th2.start();
	th3.start();
	th4.start();
	
}

}