I am new to Java and using a code given by someone. There, at the end of the code, they interrupt a thread if it has not finished. I am measuring the timing of the code.
The problem is that the Java code first issues all the threads, and then at the end it interrupts. Is interrupting necessary? Can’t we wait till all threads actually finish? Or may be just skip interrupting (these threads are running processes using process exec command and they will finish anyway).
Here is the relevant code. First the code for individual thread:
String commandString = "./script.scr ";
process = Runtime.getRuntime().exec(commandString);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((lsString = bufferedReader.readLine()) != null)
{
System.out.println(lsString);
}
try
{
process.waitFor();
}
Now the code of the part which dispatches these threads:
public void stopWhenAllTaskFinished()
{
while(notFinished) {sleep(50);} //notFinished is class variable and somewhere else it will set to false.
//now finished.
//Interrupt all the threads
for (int i=0; i<nThreads; i++) {
threads[i].interrupt();
}
}
This function is called from main class like:
obj.stopWhenAllTaskFinished()
I greatly appreciate any insight or answer.
It is not clear whether the interrupts are needed from the code that you have posted.
If
notFinishedis set tofalsewhen all threads have finished, then the interrupts are unnecessary.If
notFinishedis set tofalsewhen there is a possibility that some threads haven’t finished, then it could be necessary. Whether it is actually necessary depends on other things: