题目:网络购票
需求:
1、“桃跑跑”、“张票票”、“黄牛党”共同抢10张票
2、 限“黄牛党”只能抢一张票
解题代码:
public class Demo2 implements Runnable {
private int i;
@Override
public void run() {
while (true){
synchronized (this){
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(i == 10) {
break;
}
}
System.out.println(Thread.currentThread().getName()+"抢到第"+(i+1)+"张票,剩余"+(10-(i+1))+"张票");
i++;
//限死黄牛党囤票
if ("黄牛党".equals(Thread.currentThread().getName())){
break;
}
}
}
}
class Demo2Test{
public static void main(String[] args) {
Demo2 d = new Demo2();
Thread thread1 = new Thread(d,"桃跑跑");
Thread thread2 = new Thread(d,"张票票");
Thread thread3 = new Thread(d,"黄牛党");
thread1.start();
thread2.start();
thread3.start();
}
}