Runnable接口创建多线程例子

哈尔滨火车站下面有三个火车票代售点,假如哈尔滨到北京的火车票总共是200张,如何用程序来实现三个售票点同时卖票的功能。

public class Ticket implements Runnable{
    private int tickets = 200; //200张火车票
    boolean flag = true;
    private synchronized void sale() {
        if (tickets <= 0) {
            flag = false;
            return;
        }
        tickets--;
        System.out.print(Thread.currentThread().getName() + " sales a ticket, ");
        if (tickets > 1) System.out.println("there are " + tickets + " tickets");
        else System.out.println("there is " + tickets + " ticket");
    }
    public void run() {
        while(flag)
        {
            sale();
            try {
                Thread.sleep(100);
            }
            catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}
public class Main {
     public static void main(String[] args) {
         Ticket t = new Ticket();
         Thread th1 = new Thread(t,"system 1");
         Thread th2 = new Thread(t,"system 2");
         Thread th3 = new Thread(t,"system 3");
         th1.start();
         th2.start();
         th3.start();
     }
} 

你可能感兴趣的:(多线程)