class MyThread implements Runnable{
private int ticket = 5 ;
public void run(){
this.sale() ;
}
public synchronized void sale(){
for(int i=0;i<100;i++){
if(ticket>0){
try{
Thread.sleep(2000) ;
}catch(InterruptedException e){
e.printStackTrace() ;
}
System.out.println(Thread.currentThread().getName() + "卖票ticket = " + ticket--) ;
}
}
}
} ;
public class SaleTicket02{
public static void main(String args[]){
MyThread thr = new MyThread() ;
Thread a = new Thread(thr,"线程A") ;
Thread b = new Thread(thr,"线程B") ;
Thread c = new Thread(thr,"线程C") ;
a.start();
b.start();
c.start();
}
} ;
结果:
线程A卖票ticket = 5
线程A卖票ticket = 4
线程A卖票ticket = 3
线程A卖票ticket = 2
线程A卖票ticket = 1
为什么只有线程A卖票啊???
|
|