adding get mothods to a class extending thread
here is what i am trying to do...
i have a class to run system commands which extending the Thread class.
inside this class, a method called getOutput() that should return a string with the result.
the commands run successfully with no problems. all i want to do is to get the output stream in a string...
Thread t1 = new Command();
t1.getOutput(); // --> Not working of course because it is not a method of the thread class
Q: is that possible to do in another way... giving that the class extends Thread
Thanks
Re: adding get mothods to a class extending thread
Hello,
How are you executing these system commands?
How are you actually feeding your results into the output variable?
// Json
Re: adding get mothods to a class extending thread
Hello Json, sorry i was away for the last couple of days...
anyways, i have the following class, used to get the ls (unix command) of a file
public class TestGetDate {
String result;
String file;
Process p;
BufferedReader stdInput;
String s;
String awk;
String[] command;
public TestGetDate(String file) throws IOException{
super();
this.file = file;
p = Runtime.getRuntime().exec("ls -l " + file);
stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
result = "";
while (!procDone(p)) {
while((s=stdInput.readLine()) !=null){
result = result+s;
}
setOutput(result);
}
System.out.println(result);
stdInput.close();
}
private boolean procDone(Process p) {
try {
int v = p.exitValue();
return true;
}
catch(IllegalThreadStateException e) {
return false;
}
}
public void setOutput(String result){
this.result = result;
}
public String getOutput(){
return result;
}
}
i want this class to run as a thread but when i do, i cannot run the getOutput() method.
any ideas?
Thanks anyway
Re: adding get mothods to a class extending thread
I think it's because of how Java handles multi-threading... They have a very strict lock mechanism that prevents almost any chance of dual access, deadlocking, or an such other strange things associate with multi-threading. You can read Sun Java's Tutorial on Concurrency, but it's fairly hard to follow unless you have a fairly good knowledge of computer science and/or java.
Re: adding get mothods to a class extending thread
Make you class extend Thread. then instead of calling it using Thread t1 = new Command();
You would do something like this, if command is the class you want to run as a thread, such as your TestGetDate class.
Code :
Command c1 = new Command();
c1.start();
If I understood your problem correctly, then you can call c1.getOutput();
Regards,
Chri
Re: adding get mothods to a class extending thread
Thanks Freaky Chris, it works like a charm.
:)
Re: adding get mothods to a class extending thread
Excellent Glad I could help :)
Chris