i want to run 2 or more threads sequentially , by this I mean for example : first it should run the first thread then the second one and ... . i had used Executors.newSingleThreadExecutor(); too. I have 3 tasks :1-create a file 2- write something in that 3- read the file the create task:
public class FirstTask implements Runnable{
private CreateRoleFile createFiel = new CreateRoleFile();
@Override
public void run() {
createFiel.createFile();
}
}
the createFile() method:
public Path createFile(){
Path path = Paths.get("Files/first.txt");
if (!Files.exists(path)) {
try {
Files.createFile(path);
} catch (IOException e) {
System.out.println("something went wrong while creating first.txt .Please try again!");
}
System.out.println("thread name = "+Thread.currentThread().getName());
return path;
} else {
System.out.println("This file is already exist!!");
System.out.println("thread name = "+Thread.currentThread().getName());
return path;
}
}
the SecondTask class is :
public class SecondTask implements Runnable {
WriteRoleFile writeFile = new WriteRoleFile();
@Override
public void run() {
writeFile.Writefile("1020");
}
} and this is my main method :
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executorService1 = Executors.newSingleThreadExecutor();
Runnable firstTask =new FirstTask();
executorService1.execute(firstTask);
executorService1.shutdown();
ExecutorService executorService2=Executors.newSingleThreadExecutor();
Runnable secondTask = new SecondTask();
executorService2.submit(secondTask);
executorService2.shutdown();
ExecutorService executorService3 =Executors.newSingleThreadExecutor();
Callable thirdTask=new ThirdTask();
executorService3.submit(thirdTask);
executorService3.shutdown();
}
the ThirdTask class is :
public class ThirdTask implements Callable<String> {
ReadRoleFile readeer = new ReadRoleFile();
@Override
public String call() {
String s = readeer.readFile();
return s;
}
}
the readFile() method is :
public String readFile() {
Path path = Paths.get("Files/first.txt");
String s = "";
try {
if (Files.size(path) == 0) {
System.out.println("nothing has been wrote yet .");
} else {
try {
BufferedReader bufferedReader = Files.newBufferedReader(path);
s = bufferedReader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("thread name = " + Thread.currentThread().getName());
System.out.println(s);
return s;
}
and the out put is : This file is already exist!! thread name = pool-1-thread-1 thread name = pool-3-thread-1 null thread name = pool-2-thread-1
**I need to first the pool-1-thread-1 run and the pool-2-thread-1 because it has to write a number in a file first and then pool-3-thread1 to read from file **