1. 程式人生 > >多線程練習(簡單模擬火車站多窗口同時售票)

多線程練習(簡單模擬火車站多窗口同時售票)

火車 thread art this 模擬 練習 lis span 對象

  • 模擬火車站售票窗口同時售票

public class xianchenglianxi {
    public static void main(String arg[]){
        long begin = System.currentTimeMillis(); 
        MyThread myth_1 = new MyThread("1");        //創建線程對象
        MyThread myth_2 = new MyThread("2");
        MyThread myth_3 = new MyThread("3");
        MyThread myth_4 
= new MyThread("4"); MyThread myth_5 = new MyThread("5"); myth_1.setPriority(5); //設置線程優先級 1最低 10最高 myth_2.setPriority(6); myth_3.setPriority(10); myth_4.setPriority(1); myth_5.setPriority(8); myth_1.start(); //啟動線程 myth_2.start(); myth_3.start(); myth_4.start(); myth_5.start(); } }
class MyThread extends Thread { //繼承Thread類,為了調用其run方法 String name; int ticket = 5; //票總數 public MyThread(String name){ this.name = name; } public void run(){ //方法重寫 for(int i = ticket;i >= 0;i--){ if(i > 0){ System.out.println(
"窗口:"+name+"售票成功"+"\t"+"余票"+i); } else{ System.out.println("窗口:"+name+"售票成功\t余票 "+i+"\t窗口關閉"); } } } }

多線程練習(簡單模擬火車站多窗口同時售票)