Java之多线程Runnable(1)卖票-yellowcong

Java实现多线程的方式有三种
1、传统方式,通过继承Thread类
2、通过实现Runnable接口,然后建对象传递到new Thread(Runnable)中,启动线程
3、使用ExecutorService、Callable、Future实现有返回结果的多线程

今天,我只说通过接口Runnable的方式实现多线程的案例,PS:这玩意过几天就忘了。。。蛋疼

实现多线程买票案例

案例中,通过实现Runnable接口,然后传递票的张数,每次买票后,设定休眠100ms,这个地方,我还设置了VIP的窗口,通过Thread的setPriority方法,设定线程的优先级,线程的优先级 1-10 1 是最小的, 10 是优先级最高的,用的锁是这个实例化对象本身

package com.yellowcong.thread.tickt;

public class TicktRunnable implements Runnable{

    //票的张数
    private int count ;

    public TicktRunnable(int count) {
        super();
        this.count = count;
    }


    @Override
    public void run() {
        //这个类的自身
        while(true){
            sell();
        }
    }

    /**
     * 在run里面写上了这个本类的synchronized 后,不释放锁
     */
    public synchronized void sell(){
        if(count > 0){
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            count -- ;
            System.out.printf("%s购买的票,剩余票%d\r",Thread.currentThread().getName(),count);

        }else{
            System.out.println("票已经售完");
            Thread.currentThread().stop();
        }
    }

}

测试类

启动了4个用户,来进行买票操作

package com.yellowcong.thread.tickt;

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

public class TicketTest {


    public static void main(String[] args) {


        TicktRunnable tickt = new TicktRunnable(100);

        new Thread(tickt,"用户1").start();
        new Thread(tickt,"用户2").start();
        new Thread(tickt,"用户3").start();
        new Thread(tickt,"用户4").start();

        Thread thread1 = new Thread(tickt,"VIP用户");
        //设置线程的优先级 1-10  1 是最小的, 10 是优先级最高的
        thread1.setPriority(10);
        thread1.start();


         ExecutorService executor = Executors.newFixedThreadPool(5);
         for(int i =0;i<5;i++){
             executor.execute(tickt);
         }

         while(executor.isTerminated()){
             executor.shutdown();
             System.out.println("执行完毕");
         }


    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

狂飙的yellowcong

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值