import java.util.Random;
/*3. 某包子店铺生意火爆,现开5个窗口模拟售卖100个包子,每次每个窗口随机卖出1-5个包子,
卖完最后一个包子后提示”包子已售完”(必须全部卖出),程序结束.(要求使用Thread类和Runnable两种方式去实现)
* */
public class Demo01 {
public static void main(String[] args) {
Bao b = new Bao();
Thread t1 = new Thread(b);
Thread t2 = new Thread(b);
Thread t3 = new Thread(b);
Thread t4 = new Thread(b);
t1.setName("张三");
t2.setName("李四");
t3.setName("王五");
t4.setName("赵六");
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Bao implements Runnable {
private static int baozi = 100;
Random r = new Random();
@Override
public void run() {
int sum = 0;
while (true) {
int num = r.nextInt(4) + 1;
synchronized (this) {
if (baozi <= 0) {
break;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "卖了," + num + "个包子");
baozi = baozi - num;
sum = sum + num;
}
}
System.out.println("包子卖完了,"+Thread.currentThread().getName() + " 共卖了" + sum + "个包子!!!");
}
} |