欢迎光临散文网 会员登陆 & 注册

Runable接口共享资源的代码

2020-04-06 22:06 作者:小垃圾kiki  | 我要投稿
package cn.jd.thread;

public class TicketThreadR implements Runnable{
    
    private int num = 5;            //总共票数设定为5张
    
    @Override
    public void run() {
        for(int i=0; i<10; i++){
            if(this.num>0){            //打印买票信息
                System.out.println(Thread.currentThread().getName() + "买票: " + this.num--);
            }
        }
    }

    public static void main(String[] args) {
        TicketThreadR ticketThread = new TicketThreadR();
        
        Thread th1 = new Thread(ticketThread);    //线程一
        th1.setName("售票口一");
        Thread th2 = new Thread(ticketThread);    //线程二
        th2.setName("售票口二");
        Thread th3 = new Thread(ticketThread);    //线程三
        th3.setName("售票口三");
        
        th1.start();
        th2.start();
        th3.start();
    }
}


Runable接口共享资源的代码的评论 (共 条)

分享到微博请遵守国家法律