当前位置:神舟问>生活百科>java线程

java线程

2023-12-08 18:16:08 编辑:join 浏览量:534

问题补充说明: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线程 其它两个均未启动

java线程

问题在于线程1进入同步方法后要把票卖完后才退出,其它线程无法进入此同步方法,当线程1卖完票后,其它线程进入,但是已经没有票卖了。

我给你改了下:

packagetest;

classHyimplementsRunnable

{

privateintticket=0;

publicvoidsetTicket(intticket){

this.ticket=t360问答icket;

}

publicintgetTicket(){

returnthis.ticket;

}

publicvoidrun(){

while(true){

***.fun();

}

}

publicsynchronizedvoidfun(){

for(intx=0;x<20000;x++){

if(thi沿王酒煤衡转半该只套s.ticket>0){

try{

Thread.sleep(30);

}catch(InterruptedExceptione){

e.printS其述其息队频朝散到tackTrace();

}

System.out.p黑出罪色将倒环rintln(Thread.currentThread(相校便表益刻花).getName()+"窗口卖票"+this.ticket--);

}

错break;

}

}

吸耐}

publicclassTest

{

publicstaticvoidmain(Stringargs[]){

Hyt1三差站验若战毛=newHy();

intticket=10;

System.out.println("开始卖票,总票张数为:"+ticket);

t1.setTicket(ticket);

Threadd1=newThread(t1,"A");

Threadd2=newThread(t1,"B");

Threadd3=newThread(t1,"C");

d1.start();

d2.start();

d3.start();

}

}

标签:java,线程

版权声明:文章由 神舟问 整理收集,来源于互联网或者用户投稿,如有侵权,请联系我们,我们会立即处理。如转载请保留本文链接:https://www.shenzhouwen.com/life/230110.html
热门文章