相互访问线程

时间:2017-04-03 16:45:36

标签: java multithreading lambda

如何编写两个相互中断的线程,具体取决于哪一个先完成?以下是我尝试做的最低工作示例,但我收到错误:variable y might not have been initialized,指的是y.interrupt()

public class HelloWorld {
  public static void main(String[] args) {
    Thread x;
    Thread y;
    x = new Thread(() -> {
      try {
        // Wait for a second
        Thread.sleep(1000);
        y.interrupt();
      } catch (InterruptedException e) {
        System.out.println("X interrupted");
      }
    });

    y = new Thread(() -> {
      try {
        // Do something time-consuming, may take over a second
        Thread.sleep(2000);
        x.interrupt();
      } catch (InterruptedException e) {
        System.out.println("Y interrupted");
      }
    });
    x.start();
    y.start();
  }
}

我找到的解决方案是用数组中的两个元素替换x和y,但这看起来很丑陋和hacky。有更好的解决方案吗?

0 个答案:

没有答案