码迷,mamicode.com
首页 > 编程语言 > 详细

java多线程快速入门(九)

时间:2018-11-25 16:11:17      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:exception   code   nts   runnable   new   dem   star   trace   java   

多线程安全问题(卖火车票案例)

package com.cppdy;

class MyThread5 implements Runnable{

    private Integer ticketCount=100;
    @Override
    public void run() {
        while(ticketCount>0) {
            try {
                Thread.sleep(50);
            } catch (Exception e) {
                e.printStackTrace();
            }
            sale();
        }
    }
    
    public void sale() {
        System.out.println(Thread.currentThread().getName()+"卖出了第:"+(100-ticketCount+1)+"张票。");
        ticketCount--;
    }
}

public class ThreadDemo5 {

    public static void main(String[] args) throws Exception{
        MyThread5 mt = new MyThread5();
        Thread thread1 = new Thread(mt,"窗口1");
        Thread thread2 = new Thread(mt,"窗口2");
        thread1.start();
        thread2.start();
    }

}

 

java多线程快速入门(九)

标签:exception   code   nts   runnable   new   dem   star   trace   java   

原文地址:https://www.cnblogs.com/cppdy/p/10015530.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!