同步线程执行

同步线程执行,第1张

同步线程执行

您的代码中存在一些缺陷,这些缺陷有时会使它无法相应地工作:

  1. 您打了电话
    thread_A.start()
    然后检查
    thread_A.isAlive()
    。现在,如果
    thread_A.isAlive()
    条件检查之前thread_A已经完成,该怎么办?
    thread_B
    并且
    thread_C
    永远不会开始。您的应用程序失败
  2. 假设
    thread_A
    未完成且
    thread_A.isAlive()
    条件已通过,那么Java线程调度程序并不总是保证
    thread_B
    before的启动
    thread_C
    。同样,您的应用程序失败。
  3. 假设检查之前
    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


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5083386.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-16
下一篇 2022-11-16

发表评论

登录后才能评论

评论列表(0条)

保存