【问题标题】:Syncronize thread to wait for multiple threads同步线程等待多个线程
【发布时间】:2015-08-23 00:19:47
【问题描述】:

我有四个线程处理四个文件,然后我想要一个线程来连接这些文件。

我的解决方案是创建第五个线程(thread1)进行连接。

sum = new Thread() {
            public void run() {
                if (thread1.isAlive()) {
                synchronized (lock1) {
                        while (thread1.isAlive()) {
                            try {
                                lock1.wait();
                            } catch (InterruptedException ex) {
                                Logger.getLogger(mainClass.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                    }
                }

                if (thread2.isAlive()) {
                synchronized (lock2) {

                        while (thread2.isAlive()) {
                            try {
                                lock2.wait();
                            } catch (InterruptedException ex) {
                                Logger.getLogger(mainClass.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                    }
                }

                if (thread3.isAlive()) {
                synchronized (lock3) {
                        while (thread3.isAlive()) {
                            try {
                                lock3.wait();
                            } catch (InterruptedException ex) {
                                Logger.getLogger(mainClass.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                    }
                }

                if (thread4.isAlive()) {
                synchronized (lock4) {
                        while (thread4.isAlive()) {
                            try {
                                lock4.wait();
                            } catch (InterruptedException ex) {
                                Logger.getLogger(mainClass.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                    }
                }   //                    new MakeDataSet(path + "f4", "d4.arff");

如果线程没有按照它们的索引顺序完成(比如线程 3 在线程 2 或线程 1 之前完成,或者当线程 4 在线程 3/线程 2/线程 1 之前完成时),就会出现问题,在这种情况下程序永远不会结束。

【问题讨论】:

  • 为什么不在主线程中Thread.join()他们?

标签: java multithreading file-io synchronization


【解决方案1】:

java.lang.Thread 的方法 join() 允许您等待线程退出。你可以尝试使用这样的东西:

//wait for all threads to finish
try {
    thread1.join();
    thread2.join();
    thread3.join();
} catch (InterruptedException e) {
    e.printStackTrace();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-08
    • 2020-10-04
    相关资源
    最近更新 更多