栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

同步线程执行

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

同步线程执行

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

  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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/425919.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号