关于在特定条件下启动线程 [英] Regarding starting the threads on a condition

查看:73
本文介绍了关于在特定条件下启动线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天在一次采访中,有人问我一个无法解决的问题:

In an interview today I was asked a question I could not solve:

假设有三个线程分别名为T1,T2和T3.现在T1将 打印从1到5的数字,T2将打印从6到10的数字 和T3将打印从10到15的数字.这三个线程分别 通过说t1.start(),t2.start()和t3.start()开始,但是T3 线程应首先执行,然后执行T1线程,最后执行 应该执行T2线程.

Let's say there are three threads named T1 ,T2 and T3. Now T1 will print the numbers from 1 to 5, T2 will print the numbers from 6 to 10 and T3 will print the numbers from 10 to 15. The three threads have been started by say t1.start(), t2.start()and t3.start(), but the T3 thread should be executed first, then the T1 thread, and lastly the T2 thread should be executed.

请提供有关解决此问题的可能方法的建议.根据我的研究,有Thread.join或循环障碍的概念.请提供最佳方法的建议,如果可能的话,请显示一小段代码以更好地理解.

Please advise on possible approaches to this problem. As per my research there is the concept of Thread.join, or cyclic barriers. Please advise on the best approach, and if possible please show a small piece of code for better understanding.

推荐答案

我同意这个问题不是很好,但是您确实希望得到某种答案...

I agree that this question isn't great, but as you do want some sort of answer...

这会根据您的要求打印10-15、1-5、6-10(先按T3再按T1再按T2)(顺便说一句-T3应该从11实际打印到15吗?):

This prints out 10-15, 1-5, 6-10, as per your requirement (T3 then T1 then T2) (btw - should T3 actually print from 11 to 15?):

public class Test {
  static class Printer implements Runnable {
    private final int from;
    private final int to;
    private Thread joinThread;

    Printer(int from, int to, Thread joinThread) {
      this.from = from;
      this.to = to;
      this.joinThread = joinThread;
    }

    @Override
    public void run() {
      if(joinThread != null) {
        try {
          joinThread.join();
        } catch (InterruptedException e) { /* ignore for test purposes */ }
      }
      for (int i = from; i <= to; i++) {
        System.out.println(i);
      }
    }
  }
  public static void main(String[] args) throws InterruptedException {

    Thread T3 = new Thread(new Printer(10, 15, null));
    Thread T1 = new Thread(new Printer(1, 5, T3));
    Thread T2 = new Thread(new Printer(6, 10, T1));
    T1.start();
    T2.start();
    T3.start();
  }
}

CountdownLatch也许也是一个很好的选择.

CountdownLatch is also a good alternative here perhaps.

这篇关于关于在特定条件下启动线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆