同步线程以等待多个线程

时间:2015-06-08 13:42:24

标签: java multithreading file-io synchronization

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

我的解决方案是使第五个线程(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");

如果线程没有按照索引的顺序完成(比如thread3在thread2或thread1之前完成,或者thread4在thread3 / thread2 / thread1之前完成),则会出现问题,在这种情况下程序永远不会结束。

1 个答案:

答案 0 :(得分:4)

java.lang.Thread的方法join()允许您等待线程退出。您可以尝试使用以下内容:

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