尝试编写一个多线程java程序,但遇到一些问题,我的主要多线程类工作正常,但如果我从main调用它,它会启动所有线程并移至下一个函数,我需要它不要继续移动,直到所有线程都已完成。 read 获取传递的文件路径 read(String, String)
Thread one = new Thread(new Runnable() {
public void run()
{
System.out.println("Starting thread 1");
read(expiredOneYear, master1);
System.out.println("Finished thread 1");
}
});
Thread two = new Thread(new Runnable() {
public void run()
{
System.out.println("Starting thread 2");
read(expiredOneAndQuarterYear, master2);
System.out.println("Finished thread 2");
}
});
Thread three = new Thread(new Runnable() {
public void run()
{
System.out.println("Starting thread 3");
read(expiredOneAndHalfYear , master3);
System.out.println("Finished thread 3");
}
});
Thread four = new Thread(new Runnable() {
public void run()
{
System.out.println("Starting thread 4");
read(expiredOneAnd3QuarterYear , master4);
System.out.println("Finished thread 4");
}
});
// start threads
one.start();
two.start();
three.start();
four.start();
下面是 main 中发生的事情
CSVcompare.run(threadCount, mode, fileLocation);
CSVpattern.run(fileLocation);
我不希望 CSVpattern.run() 在 CSVcompare.run() 中的所有线程都完成之前启动,否则它将无法为 CSVpattern.run() 准备好某些数据
最佳答案
在运行结束时添加对 join()
的调用。 join()
方法等待线程完成。
try
{
one.join();
two.join();
three.join();
four.join();
}
catch (InterruptedException e)
{
System.out.println("Interrupt Occurred");
e.printStackTrace();
}
如果你想忽略中断(可能至少应该找出它被中断的原因,但这会起作用)
boolean done = false;
while (!done)
{
try
{
one.join();
two.join();
three.join();
four.join();
done = true;
}
catch (InterruptedException e)
{
// Handle interrupt determine if need to exit.
}
}
https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#join()
关于Java多线程等待线程完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43151455/