public class TicketRunnable implements Runnable{
private int tickets = 100;
@Override
public void run() {
while(true){
if(tickets > 0){
try {
Thread.sleep(1000);//必须加这个,否则不一定出现负数-----语句1
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"正在卖第"+tickets--+"张的票");---语句2
}else{
break;//必须加这个,否则无法跳出循环,造成死机
}
}
}
}
测试代码
public class TicketDemo {
public static void main(String[] args) {
TicketRunnable runnable = new TicketRunnable();
Thread t1 = new Thread(runnable, "窗口1");
Thread t2 = new Thread(runnable, "窗口2");
Thread t3 = new Thread(runnable, "窗口3");
t1.start();
t2.start();
t3.start();
}
}
|
|