Newbie to multi-threading please direct me :)
Hi,
As the title says I am new to java multi-threaded programming.
Here is what I need to do. I need to execute multiple threads from a simple java method and then watch from the same method when all the executed threads are finished and as every thread ends this thread should pass a value back to my function.
Could this be accomplished and if yes can someone direct how I can accomplish this.
Here some of the code I am trying to get to work:
Code:
package executor;
import java.io.*;
class StreamGobbler extends Thread {
InputStream is;
String type;
StreamGobbler(InputStream is, String type) {
this.is = is;
this.type = type;
}
@Override
public void run() {
try {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(type + ">" + line);
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
/**
*
* @author kminev
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException, InterruptedException {
// TODO code application logic here
File f;
Writer wr=null;
f = new File("myScript.sh");
if (!f.exists()) {
f.createNewFile();
}
//StringBuilder sb = new StringBuilder();
wr = new BufferedWriter(new FileWriter(f));
wr.write("this goes to a bash script that will be executed as a thread");
wr.close();
String strCommand = "bash myScript.sh";
//System.out.println("Command: " + strCommand);
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(strCommand);
StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");
// any output?
StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");
System.out.println("KICK THEM OFF");
// kick them off
errorGobbler.start();
outputGobbler.start();
System.out.println("AFTER KICK OFF BLOCK");
// any error???
int exitVal = proc.waitFor();
System.out.println("ExitValue: " + exitVal);
if(exitVal == 0){
f.delete();
}
}
}
If I have a for loop which will call the code in main x amount of times how can I know when all threads are return and most importantly return a values from each thread?
Thanks in advance.