/*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+"个包子");
}
} |
|