2013-06-20 184 views
0

我正面临一个多线程问题。如何让线程等待状态达到第一个线程完成

我有10个Threads.When我们strat应用程序的第一个线程将尝试创建该文件夹。 意思是当剩余的线程尝试将文件移动到该文件夹​​,在创建folder.so之前,我得到NulpointerException。如何停止将文件夹保存到文件夹创建者线程完成。

这样的代码:

Static int i; 
moveFile() 
{ 
if(i==1){ 
create(); 
} 
move(){ 
} 
} 
+3

直到创建的文件夹,不要启动线程? – assylias

回答

2

您可以通过多种方式做到这一点。

  1. 新建文件夹的检查在你的线程存在,那么将文件转换成它
  2. 运行第二线程创建唯一的文件夹后,所以,这将永远不会发生。如果有多个文件夹和这么多的文件疗法则创建文件夹的complition后推出新的线程在第二线程dedicatly文件推到该特定文件夹
2

创建大小的锁存器(countdown latch)1.

创建文件夹后,在创建文件夹的线程中调用countdown()方法。在开始任何处理(如移动文件)之前,在所有其他线程中调用闩锁上的await()方法。

有很多其他的方法可以做到。如果可能的话,选择最简单的方法(产生移动文件et-all的线程/任务,只有在文件夹被创建后)

0

我觉得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! 
    } 
} 

}

+0

连接可能不是很好的解决方案,如果创建文件夹的线程还有一些其他任务也可以做。@Scorpion建议的.CoundownLatch似乎更好的方式来处理这个 – veritas

+0

正如@Scorpion在他的回答中所述,有其他几种方法可以做到这一点,而且他的方式在某些情况下可能会更好。我只是试图提供一个完全按照他/她的要求提供的答案 - 为了知识的缘故,“如何停止让文件夹创建文件夹线程完成”。 – Elist