java 多线程同步 通过继承Thread的方式 示例

public class SaleTicketThread{
    public static void main(String[] args) {

        TicketThread t1 = new TicketThread("window_1");
        TicketThread t2 = new TicketThread("window_2");
        TicketThread t3 = new TicketThread("window_3");
        TicketThread t4 = new TicketThread("window_4");

        t1.start();
        t2.start();
        t3.start();
        t4.start();

    }
}

class TicketThread extends Thread{

    //tickets
    static int tickets = 50;

    //lock object
    static Object obj = new Object();

    private String name;

    public TicketThread(String name){
        this.name = name;
    }

    @Override
    public void run(){
        while (true){

            //Synchronized
            synchronized (obj){
                if (tickets > 0){
                    System.out.println(name+" are sold "+"NO."+tickets--);
                }else{

                    break;
                }
            }

            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

        System.out.println(name+" all tickets were sold out");
    }
}
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页