A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© wolfking0608 中级黑马   /  2016-10-10 11:11  /  1276 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

/*3. 某包子店铺生意火爆,现开5个窗口模拟售卖100个包子,每次每个窗口随机卖出1-5个包子,
卖完最后一个包子后提示”包子已售完”(必须全部卖出),程序结束.(要求使用Thread类和Runnable两种方式去实现)

* */
public class 多线程_卖包子 {
   @SuppressWarnings("static-access")
public static void main(String[] args) throws InterruptedException {
        MyThread08 t1 = new MyThread08();
        MyThread08 t2 = new MyThread08();
        MyThread08 t3 = new MyThread08();
        MyThread08 t4 = new MyThread08();
        MyThread08 t5 = new MyThread08();
         t1.setName("窗口一:");
         t2.setName("窗口二:");
         t3.setName("窗口三:");
         t4.setName("窗口四:");
         t5.setName("窗口五:");
          t1.start();
          t2.start();
          t3.start();
          t4.start();
          t5.start();
          Thread.currentThread().sleep(1100);
          System.out.println("包子卖完了");
       
}
}
class MyThread08 extends Thread{
        static int num=100;
        public void run(){
                int count=0;
                while(true){
                        synchronized(Thread.class){
                                if(num<=0){
                                        break;
                                }
                                try {
                                        Thread.sleep(10);
                                } catch (InterruptedException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                }
                                count++;
                                System.out.println(Thread.currentThread().getName()+"卖出了,第"+count+"个包子");
                                num--;
                       
                        }
                }
                System.out.println(Thread.currentThread().getName()+"-------------------共卖出了"+ count+"个包子");
        }
}

1 个回复

倒序浏览
没意思,用两个线程做包子,两个线程卖包子可好
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马