栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

多线程卖票/synchronized的使用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

多线程卖票/synchronized的使用

package com.duia.statistic.common.achievement.data;

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

public class test {


    public static void main(String[] args) {
        Test1 t1=new Test1();
        t1.setName("张无忌");
        Test1 t2=new Test1();
        t2.setName("赵敏");
        Test1 t3=new Test1();
        t3.setName("韦一笑");
        ExecutorService fixedThreadPool= Executors.newFixedThreadPool(3);

            fixedThreadPool.execute(t1);
            fixedThreadPool.execute(t2);
            fixedThreadPool.execute(t3);

    }



}
 class Test1 implements Runnable {
    private String name;
    private static Integer num=10;

     public Integer getNum() {
         return num;
     }

     public void setNum(Integer num) {
         this.num = num;
     }

     public String getName() {
         return name;
     }

     public void setName(String name) {
         this.name = name;
     }
    final  private Object a=0;
     @Override
     public    void run() {
         while (true) {
             synchronized (a){
                 if (num > 0) {//当剩余票大于0张时执行
                     try {
                         Thread.sleep(100);
                     } catch (InterruptedException e) {
                         e.printStackTrace();
                     }
                     System.out.println(this.getName() + "正在卖第" + num + "张票");
                     num--;
                 }
             }

         }


 }
 }

赵敏正在卖第10张票
韦一笑正在卖第9张票
韦一笑正在卖第8张票
韦一笑正在卖第7张票
张无忌正在卖第6张票
张无忌正在卖第5张票
韦一笑正在卖第4张票
韦一笑正在卖第3张票
韦一笑正在卖第2张票
韦一笑正在卖第1张票

新手注意的是实际应用中不要像我一样手动创建ExecutorService ,无边界的线程池默认值容易引起oom(挂了),应该去学习使用spring的

ThreadPoolTaskExecutor

为什么锁变量a而不用this,this会出现不安全,具体为什么我还没弄明白。

注意变量static 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/328301.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号