2021-08-30

多线程模拟购票系统、线程池

(1)购票方法

package com.hw.Test3;

public class ByTicket {
    
    
    private int nubTicket = 20;

    public synchronized int getNubTicket() {
    
    //synchronized 枷锁 保护数据的安全性
        if (nubTicket < 1) {
    
    
            throw new RuntimeException("没票啦.......");
        }
        nubTicket--;
        return nubTicket;
    }
}

(2)多线程处理

package com.hw.Test3;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test1 {
    
    
    public static void main(String[] args) {
    
    
        ByTicket bt = new ByTicket();
        ExecutorService service = Executors.newFixedThreadPool(5);//线程池设置5个线程量

        for (int i = 1; i < 6; i++) {
    
    
            int id = i;//标记线程-号
            service.submit(new Runnable() {
    
    
                @Override
                public void run() {
    
    
                    while (true) {
    
    
                        int num = bt.getNubTicket();
                        System.out.println("线程" + id + "买到了一张票,系统还剩-->" + num + "张票!");
                    }
                }
            });
        }
        service.shutdown();//关闭多线程问题
    }
}

![运行结果](https://img-blog.csdnimg.cn/6288f58f08cd4f98b7d66a4f5225198f.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBAV2xkS2lkX3p4eQ==,size_20,color_FFFFFF,t_70,g_se,x_16)

猜你喜欢

转载自blog.csdn.net/m0_45256755/article/details/119989490
今日推荐