-2

My main method is trying to start and terminate each and every thread in sequential order before it goes onto the next one on the line below. This means that the object guest0 is stuck waiting for one of the DeskEmployee objects to release a semaphore it has acquired, and the rest of the program simply fails to execute. How do I get it not to do this?

public static void main(String[] args) {
        Project2 proj = new Project2();
        Project2.Guest guest0 = proj.new Guest();
        Project2.Guest guest1 = proj.new Guest();
        Project2.Guest guest2 = proj.new Guest();
        Project2.Guest guest3 = proj.new Guest();
        Project2.Guest guest4 = proj.new Guest();
        Project2.Guest guest5 = proj.new Guest();
        Project2.Guest guest6 = proj.new Guest();
        Project2.Guest guest7 = proj.new Guest();
        Project2.Guest guest8=proj.new Guest();
        Project2.Guest guest9 = proj.new Guest();
        Project2.Guest guest10 = proj.new Guest();
        Project2.Guest guest11 = proj.new Guest();
        Project2.Guest guest12 = proj.new Guest();
        Project2.Guest guest13 = proj.new Guest();
        Project2.Guest guest14 = proj.new Guest();
        Project2.Guest guest15 = proj.new Guest();
        Project2.Guest guest16 = proj.new Guest();
        Project2.Guest guest17 = proj.new Guest();
        Project2.Guest guest18 = proj.new Guest();
        Project2.Guest guest19 = proj.new Guest();
        Project2.Guest guest20 = proj.new Guest();
        Project2.Guest guest21 = proj.new Guest();
        Project2.Guest guest22 = proj.new Guest();
        Project2.Guest guest23 = proj.new Guest();
        Project2.Guest guest24 = proj.new Guest();
        Project2.DeskEmployee employee0=proj.new DeskEmployee(0);
        Project2.DeskEmployee employee1=proj.new DeskEmployee(1);
        Project2.Bellhop bellhop0=proj.new Bellhop(0);
        Project2.Bellhop bellhop1=proj.new Bellhop(1);
        guest1.run();
        guest2.run();
        guest3.run();
        guest4.run();
        guest5.run();
        guest6.run();
        guest7.run();
        guest8.run();
        guest9.run();
        guest10.run();
        guest11.run();
        guest12.run();
        guest13.run();
        guest14.run();
        guest15.run();
        guest16.run();
        guest17.run();
        guest18.run();
        guest19.run();
        guest20.run();
        guest21.run();
        guest22.run();
        guest23.run();
        guest24.run();
        employee0.run();
        employee1.run();
        bellhop0.run();
        bellhop1.run();
    }
4

1 回答 1

0

你说这些是线程?你通过run()?

那是行不通的。基本上,直接调用run()(而不是通过 aThreadstart()方法)将在当前线程上按顺序运行任务,而不是产生一个新线程。如果第一个任务恰好被阻止等待其他人做某事,那么你就陷入了僵局。由于其他任务在第一个任务完成后才会开始运行,因此无法解除对主线程的阻塞。

而不是whatever.run(),尝试new Thread(whatever).start()。(或者,如果您的类Thread出于某种原因扩展,只需whatever.start(). 但最好将它们修复为实现;除非您更改线程的工作方式,否则Runnable不要扩展。)Thread

于 2012-11-03T09:00:55.177 回答