我正面临一个多线程问题。如何让线程等待状态达到第一个线程完成
我有10个Threads.When我们strat应用程序的第一个线程将尝试创建该文件夹。 意思是当剩余的线程尝试将文件移动到该文件夹,在创建folder.so之前,我得到NulpointerException。如何停止将文件夹保存到文件夹创建者线程完成。
这样的代码:
Static int i;
moveFile()
{
if(i==1){
create();
}
move(){
}
}
我正面临一个多线程问题。如何让线程等待状态达到第一个线程完成
我有10个Threads.When我们strat应用程序的第一个线程将尝试创建该文件夹。 意思是当剩余的线程尝试将文件移动到该文件夹,在创建folder.so之前,我得到NulpointerException。如何停止将文件夹保存到文件夹创建者线程完成。
这样的代码:
Static int i;
moveFile()
{
if(i==1){
create();
}
move(){
}
}
您可以通过多种方式做到这一点。
创建大小的锁存器(countdown latch)1.
创建文件夹后,在创建文件夹的线程中调用countdown()
方法。在开始任何处理(如移动文件)之前,在所有其他线程中调用闩锁上的await()
方法。
有很多其他的方法可以做到。如果可能的话,选择最简单的方法(产生移动文件et-all的线程/任务,只有在文件夹被创建后)
我觉得Thread.join()就是你要找的。它在线程上执行wait()(可能有超时),直到执行结束。
将“文件夹线程”的引用传递给每个其他“文件线程”,然后join()它。
例子:
public class JoinThreads {
static ArrayList<FileThread> fthreads = new ArrayList<FileThread>();
public static void main(String[] args) {
Thread folderThread = new Thread() {
@Override
public void run() {
// Create the folder
}
}.start();
// Add new threads to fthreads, pass folderThread to their constructor
for (FileThread t : fthreads) {
t.start();
}
}
public class FileThread extends Thread {
Thread folderThread;
File file;
public FileThread(Thread folderThread, File file) {
this.folderThread = folderThread;
}
@Override
public void run() {
try {
folderThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
// Save the file, folder should already exist!
}
}
}
直到创建的文件夹,不要启动线程? – assylias