问题补充说明:class Hy implements Runnable{ private int ticket = 0 ; public void setTicket(int ticket){ this.ticket = ticket; } public int getTicket(){ return this.ticket; } public void run(){ ***.fun(); } public synchronized void fun(){ for(int x=0;x<20000;x++){ if(this.ticket>0){ try{ Thread.sleep(30); }catch(InterruptedException e){ e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "窗口卖票" + this.ticket--); } } }}public class StringBufferDemo01{ public static void main(String args[]){ Hy t1 = new Hy(); int ticket = 10; System.out.println("开始卖票,总票张数为:" + ticket ); t1.setTicket(ticket); Thread d1 = new Thread(t1,"A"); Thread d2 = new Thread(t1,"B"); Thread d3 = new Thread(t1,"C"); d1.start(); d2.start(); d3.start(); }}此道程序为什么只启动d1线程 其它两个均未启动
问题在于线程1进入同步方法后要把票卖完后才退出,其它线程无法进入此同步来自方法,当线程1卖完票后,360问答其它线程进入,但是已经没有票卖了。
我给你改了下:
packagetest;
c底雷lassHyimplementsRunnable
{
privateint血证ticket=0;
publicvoidsetTicket(intti举纸始东右研磁的关油cket){
this.ticket=ticket;
}
publicintgetTicket(){
returnthis.ticket;
}
publicvoidrun(){
while(tru相反跑况哪东校纪只喜e){
***.fun();
}
}
publicsynchronizedvoidfun(){
for(intx=0;x<20000;x++){
if(this.ticket>0){
try{
Thread.sleep(30);
}catch(Interr促附胞器切盾垂械弱事垂uptedExceptione){
e.printStackTrace();
}
System.out.p青rintln(Thread.currentThread().getName()+"窗口卖票"+t营每呼具仍唱his.ticket--);
}
break;
}
}
}
publicclassTest
{
publics师备里益taticvoidmain(Stringargs[]){
Hyt1=newHy();
intticket=10;
System.out.p飞讨低谓rintln("开始卖票,总票张数为:"+ticket);
t1.setT点序章接icket(ticket);
Threadd1=newThread(t1,"A");
Threadd2=newThread(t1,"B")协料;
Threadd3=n包改景充花ewThread(t1,"C");
d1.start宁岁();
d2.st衡判守广让居激开art();
d3.start();
}
}
标签:java,线程