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.
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.