首页 > 试题广场 >

请阅读下列给出的程序,并根据程序的功能改正程序中的错误

[问答题]

请阅读下列给出的程序,并根据程序的功能改正程序中的错误

改写以下多线程程序,使之能够实现在四个售票处,发售某日某次列车的共100张票。

public class ThreadDemo{

public void main(String [] args)       {

new ThreadTest().start();              new ThreadTest().start();

new ThreadTest().start();              new ThreadTest().start();

}

}

class ThreadTest extends Thread {

private int tickets=100;

public void run()       {

while(1 )              {

if(tickets>0)

System.out.println(Thread.currentThread().getName()

+" is saling ticket " + tickets--);

}

}

}


下面的老哥,你的这个不对呀,每个线程都卖100张票,应该改成实现runnable接口
发表于 2018-09-06 08:02:00 回复(0)


public class ThreadDemo{

public void main(String [] args) {

new ThreadTest().start();              new ThreadTest().start();
new ThreadTest().start();              new ThreadTest().start();

}

}

class ThreadTest extends Thread {

private int tickets=100;

public void run()       synchronized (tickets){

while(true)              {

if(tickets>0)

System.out.println(Thread.currentThread().getName()

+" is saling ticket " + tickets--);

}

}

}


发表于 2017-11-24 22:17:02 回复(1)
public class Exam377{ public static void main(String[] args) { ThreadTest win = new ThreadTest(); Thread twin1 = new Thread(win,"1号窗口"); Thread twin2 = new Thread(win,"2号窗口"); Thread twin3 = new Thread(win,"3号窗口"); Thread twin4 = new Thread(win,"4号窗口"); twin1.start(); twin2.start(); twin3.start(); twin4.start(); } } class ThreadTest extends Thread{ Object obj=new Object(); private int tickets =100; public void run(){ while(true){ synchronized(obj){ if(tickets>0){ try { Thread.sleep(100); /*每次运行就沉睡一下,让结果更加明显*/ } catch(Exception e) { } System.out.println(Thread.currentThread().getName()+"is saling ticket"+tickets--); } else break; } } } }
编辑于 2017-11-19 18:09:47 回复(0)