Java多线程学习笔记_线程安全

一、买票案例的的实现

说明:多个窗口同时卖100张票,卖完即停止售票。

思路:

Java多线程学习笔记_线程安全

public class MyRunnable implements Runnable{
    private int ticket = 100;
    @Override
    public void run() {
        while (ticket >= 0) {
            if(ticket == 0){
                break;
            }else {
                ticket--;
                System.out.println(Thread.currentThread().getName() + "卖了一张票,还剩" + ticket + "张");
            }
        }

    }
}

public class Demo {
    public static void main(String[] args) {
        MyRunnable mr1 = new MyRunnable();

        Thread t1 = new Thread(mr1);
        Thread t2 = new Thread(mr1);
        Thread t3 = new Thread(mr1);

        t1.setName("#窗口一#");
        t2.setName("##窗口二##");
        t3.setName("###窗口三###");

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

 

上一篇:30行Python代码爬取英雄联盟全英雄全皮肤


下一篇:微信小程序开发之菜单的创建