//演示示例11 练习7
public class Test implements Runnable{ //1,实现Runnable接口
private int count=50; //记录剩余票数
private int num = 0; //记录买到第几张票
//1,同步代码块
public void run(){
while (count>0) {//synchronized (this){}放在while里面
synchronized (this){
num++;
count--;
if(count<0)
return;
try {
Thread.sleep(500); // 模拟网络延时
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "抢到第" + num
+ "张票,剩余" + count + "张票!");
//黄牛党仅限买一张票
if(Thread.currentThread().getName().equals("黄牛党")){
return ;
}
}
}
}
//2,同步方法
/* public void run() {
while (count>0) {
buyTicket();
}
}
public synchronized void buyTicket(){
num++;
count--;
if(count<0)
return;
try {
Thread.sleep(500); // 模拟网络延时
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "抢到第" + num
+ "张票,剩余" + count + "张票!");
}*/
public static void main(String[] args) {
Test t = new Test(); //3,创建实现类对象
Thread p1= new Thread(t,"桃跑跑"); //4,把对象装进线程中
Thread p2= new Thread(t,"张票票");
Thread p3= new Thread(t,"黄牛党");
System.out.println("********开始抢票********");
p1.start();//调用方法
p2.start();
p3.start();
}
}
?
|