class TicketSouce implements Runnable
{
private int ticket=10;//火车票的总张数
public void run(){
while (true){
synchronized (this){
if (ticket > 0){
System.out.println(Thread.currentThread().getName() + "号窗口卖出" + this.ticket-- + "号票");
}
else{
System.out.println(Thread.currentThread().getName() + "火车票已售完");
break;
}
}
try{
Thread.sleep(1000);
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
{
private int ticket=10;//火车票的总张数
public void run(){
while (true){
synchronized (this){
if (ticket > 0){
System.out.println(Thread.currentThread().getName() + "号窗口卖出" + this.ticket-- + "号票");
}
else{
System.out.println(Thread.currentThread().getName() + "火车票已售完");
break;
}
}
try{
Thread.sleep(1000);
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
main中调用:
new Thread(mt,"a").start();
new Thread(mt,"b").start();
new Thread(mt,"c").start();