【问题标题】:Regarding joining of threads in an order关于按顺序连接螺纹
【发布时间】:2013-02-03 04:32:56
【问题描述】:

我是线程世界的新手,仍在学习,因为我正在研究线程的概念并加入其他线程等待较早线程完成并从那里加入的地方,请您告诉我我想启动三个线程 T1,T2,T3,一旦 T1 完成,t2 将在其中启动。

【问题讨论】:

  • 如果你只想一次运行一个线程,为什么还要创建三个线程呢?
  • 我觉得还有T3。
  • 你可以在这里找到一个简单的解决方案:stackoverflow.com/a/13695190/469220
  • @Vlad 你可以在同一个线程中执行 T1 和 T2 任务,因此有 2 个线程而不是 3 个。
  • @UmNyobe,是的,你是对的。没想到。

标签: java multithreading


【解决方案1】:

据我了解,您希望等到线程 1 完全完成后再启动线程 2,而线程 3 可以在任何地方运行。我认为可以满足您的问题的简单代码:

Thread thread1 = new Thread1();
Thread thread2 = new Thread2();
Thread thread3 = new Thread3();
thread3.start();
thread1.start();
try {
  thread1.join();
  thread2.start();
} catch (InterruptedException e) {
  //if you do not use thread1.interrupt() this will not happen.
}

【讨论】:

    【解决方案2】:

    您可以在多个线程完成后使用 Barriers 启动一些操作(可能是另一个线程)。

    查看:http://programmingexamples.wikidot.com/java-barrier 了解更多信息。

    但是只等待一个线程真的没有多大意义......

    【讨论】:

      【解决方案3】:

      做这样的事情:

              Thread T1 = new Thread(new ThreadExm);  // where ThreadExm implements Runnable
              Thread T2 = new Thread(new ThreadExm);
      
              try {
                  // Start the thread1 and waits for this thread to die before
                  // starting the thread2 thread.
                  T1.start();
                  T2.join();
      
                  // Start thread2 when T1 gets completed
                  thread2.start();
              } catch (InterruptedException ex) {
                  ex.printStackTrace();
              }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-31
        • 2023-02-10
        • 1970-01-01
        相关资源
        最近更新 更多