天天看點

Runnable接口建立多線程例子

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();
     }
}      

繼續閱讀