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

一、买票案例的的实现

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

思路:

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

猜你喜欢

转载自blog.csdn.net/qq_43191910/article/details/114964791