多线程卖票/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 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值