【发布时间】: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