简体   繁体   中英

how to make threads wait state upto first thread complete

i am facing one multiThreaded issue.

i have 10 Threads.when we strat application the first thread will try to create the folder. mean while remaining thread try to move the file to that folder,before creating folder.so i am getting NulpointerException. how to stop remaining theads up to folder creater thread completes.

code like this:

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

You can do it in many ways.

  1. Make a check of folder exist in your thread then place file into it
  2. Run 2nd thread only after creation of folder so that this will never happen. If there are multiple folders and so many files are ther then launch new thread after complition of creation of folder where the 2nd thread dedicatly push files into that specific folder

Create a latch ( countdown latch ) of size 1.

In the thread creating the folder call the countdown() method on the latch after the folder has been created. In all other threads call the await() method on the latch before beginning any processing like moving the file.

There are zillion other ways to do it. If it's possible choose the simplest approach (spawn the threads/ tasks which move files et-all only after the folder is created)

I think Thread.join() is what you are looking for. It performs wait() on the thread (possibly with timeout) until it's execution ends.

Pass a reference of the "folder thread" to each of the other "file threads", and join() it.

Example:

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!
    }
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM