您的代码中存在一些缺陷,这些缺陷有时会使它无法相应地工作:
- 您打了电话
thread_A.start()
然后检查了thread_A.isAlive()
。现在,如果thread_A.isAlive()
条件检查之前thread_A已经完成,该怎么办?thread_B
并且thread_C
永远不会开始。您的应用程序失败。 - 假设
thread_A
未完成且thread_A.isAlive()
条件已通过,那么Java线程调度程序并不总是保证thread_B
before的启动thread_C
。同样,您的应用程序失败。 - 假设检查之前
thread_B
开始,thread_C
并且如果检查thread_B
完成之前thread_B.isAlive()
,则if
条件失败并且thread_D
永远不会开始。同样,您的应用程序失败。
现在需要考虑的一点是:
在join()
调用其方法之后,无需检查线程是否处于活动状态。这是不必要的运行时开销。
编辑
好,这是代码的修改版本。.我希望它可以让您了解线程的动态:
class RobotController implements Runnable{ private final Object lock = new Object(); private void notifyThread() { synchronized(lock) { lock.notify(); } } public void run() { synchronized(lock) { try { System.out.println(Thread.currentThread().getName() + " started"); lock.wait(); System.out.println(Thread.currentThread().getName()+ " stopped"); } catch (InterruptedException ex) { ex.printStackTrace(); } } } public static void main(String args[]) throws InterruptedException { RobotController rca = new RobotController(); RobotController rcb = new RobotController(); RobotController rcc = new RobotController(); RobotController rcd = new RobotController(); Thread thread_A = new Thread(rca,"Thread A"); Thread thread_B = new Thread(rcb,"Thread B"); Thread thread_C = new Thread(rcc,"Thread C"); Thread thread_D = new Thread(rcd,"Thread D"); thread_A.start(); while (thread_A.getState() != Thread.State.WAITING) { Thread.sleep(100); } thread_B.start(); thread_C.start(); while (thread_B.getState() != Thread.State.WAITING && thread_C.getState() != Thread.State.WAITING) { Thread.sleep(100); } thread_D.start(); while (thread_D.getState() != Thread.State.WAITING) { Thread.sleep(100); } rcd.notifyThread(); thread_D.join(); rcc.notifyThread(); thread_C.join(); rcb.notifyThread(); thread_B.join(); rca.notifyThread(); }}
这是输出:
Thread A startedThread B startedThread C startedThread D startedThread D stoppedThread C stoppedThread B stoppedThread A stopped
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)