带有嵌入式线程的Java-While循环错误

带有嵌入式线程的Java-While循环错误,java,multithreading,while-loop,Java,Multithreading,While Loop,我在下面有一段代码,它计算是否完成了三个线程,如果是,则继续代码。问题是,当我在if语句之前包含某种print语句时,它照常工作。然而,当我不包括印刷品时,它将永远持续下去。这是: while (!are_we_done) { System.out.println(are_we_done); if (thread_arr[0].are_we_done==true && thread_arr[1].are_we_done==true && threa

我在下面有一段代码,它计算是否完成了三个线程,如果是,则继续代码。问题是,当我在if语句之前包含某种print语句时,它照常工作。然而,当我不包括印刷品时,它将永远持续下去。这是:

while (!are_we_done) {
    System.out.println(are_we_done);
    if (thread_arr[0].are_we_done==true && thread_arr[1].are_we_done==true && thread_arr[2].are_we_done==true) {
        are_we_done=true;
    }
}
有什么线索吗?
提前感谢您提供的任何帮助/建议。

问题是我必须将thread类中的
are\u we\u done
变量指定为
volatile

您处理线程的工作非常出色-google表示“忙等待”

  • 在主线程中引入'latch=new CountDownLatch()'变量
  • 将其传递到所有线程中
  • 线程调用“lock.countDown()”完成时
  • 在主线程中,等待所有生成的线程完成“latch.await(…)”
例如:

public static void main(String... args) throws Exception {
    Thread[] threads = new Thread[3];
    CountDownLatch latch = new CountDownLatch(threads.length);

    for (int i = 0; i < threads.length; i++) {
        threads[i] = new Thread(new YourRunnable(latch));
        threads[i].start();
    }

    while (!latch.await(1000)) {
        System.out.println("Not complete yet");
    }

    System.out.println("Complete!");
}

public class YourRunndable implements Runnable {
    ... // fields + constructor

    public void run() {
        try {
            ... // do your staff
        } finally {
            latch.countDown();
        }
    }
}
publicstaticvoidmain(String…args)引发异常{
线程[]线程=新线程[3];
CountDownLatch闩锁=新的CountDownLatch(threads.length);
对于(int i=0;i
请参阅:在这种情况下,如何将信息从阵列中的线程传输到主线程?简而言之,使用共享数据结构(例如集合、队列、字段)。阅读-这是多线程的最佳指南。一个小时的阅读和测试,但生活得更远要简单得多。