public class FinalAttack {
public static void main(String[] args) {
buyT station =new buyT();
new Thread(station,"a").start();
new Thread(station,"b").start();
new Thread(station,"c").start();
}
}
class buyT implements Runnable{
private int tnum=10;
boolean flag=true;
@Override
public void run() {
while (flag){
try {
buy();
//Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private synchronized void buy() throws InterruptedException {
if(tnum<=0){
flag=false;
return;
}
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName()+"拿到"+tnum--);
}
}
上方代码运行结果为
我想实现的效果是模拟抢票:
为什么把sleep的位置换一下就可以实现了?
public class FinalAttack {
public static void main(String[] args) {
buyT station =new buyT();
new Thread(station,"a").start();
new Thread(station,"b").start();
new Thread(station,"c").start();
}
}
class buyT implements Runnable{
private int tnum=10;
boolean flag=true;
@Override
public void run() {
while (flag){
try {
buy();
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private synchronized void buy() throws InterruptedException {
if(tnum<=0){
flag=false;
return;
}
System.out.println(Thread.currentThread().getName()+"拿到"+tnum--);
}
}
希望能得到一个便于理解的回答,谢谢。