/*
有100个限量版的水杯,但是只能通过实体店和官网才能进行购买,并且分别统计卖了多少。
请用线程进行模拟并设置线程名称用来代表售出途径,再将信息打印出来。
比如(实体店卖出第1个,总共剩余n个..)
*/
public class Test {
public static void main(String[] args) {
Cup cup = new Cup();
new Thread(cup,"实体店").start();
new Thread(cup,"官网").start();
}
}
class Cup implements Runnable {
private int num = 100;
private int countGw = 0;//用于统计官网销售的水杯的数量
private int countSt = 0;//用于统计实体店销售的水杯的数量
@Override
public void run() {
while(true) {
synchronized (this) {
String threadName = Thread.currentThread().getName();
if(num<=0) {
if("实体店".equals(threadName)) {
System.out.println(threadName+"总共销售了: "+ countSt+" 个水杯!");
} else {
System.out.println(threadName+"总共销售了: "+ countGw+" 个水杯!");
}
break;
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
if("实体店".equals(threadName)) {
countSt++;
} else {
countGw++;
}
System.out.println(Thread.currentThread().getName()+"卖出第"+(100-num+1)+"个,总共剩余 "+(--num)+" 个..");
}
}
}
} |
|