Java threads problem
I have a problem with java threads:
public class MyClass{
public void Core(){
runTools(); //here I would like to call runTools() method
}
public vo开发者_如何学Cid runTools(){
final String run_tool ="cmd.exe /C sources.exe";
Runnable doRun = new Runnable() {
public void run() {
try {
Process tool_proc = Runtime.getRuntime().exec(run_tool);
}
catch (IOException e) {
e.printStackTrace();
}
}
};
Thread th = new Thread(doRun);
th.start();
}
}
If I do this, then I don't know why, but the thread doesn't work. Please give me some ideas to create a thread. I have already been seen lots of examples, but I should some code such as my example here. Thanks!
At first, if you just want to execute an external command and do not bother about its output*, then using a dedicated thread is unnecessary, since the process itself will already run in parallel to your application, so the exec()
call will not really hang your programm.
Nevertheless your code looks correct to me. You should check the working directory of your application (maybe cmd.exe
cannot find your sources.exe
) and evaluate the output the process you start gives you, by directing the streams of tool_proc.getErrorStream()
and tool_proc.getInputStream()
to System.out
or logging them.
EDIT:
* The Java documentation states you always should read the InputStream
s of your processes as failing to do so might result in filling up a system buffer, which will eventually hang the process.
problem 1 You create object for Runnable Interface,that is never possible.
Runnable *obj=new Runnable(); // this is not correct
problem 2 You write definition for Run() method with in the another method runTools()
we can create object for a class that implements The Runnable interface.
Due to these your code is not working.
Try the fallowing way
public class MyClassName1 implements Runnable
{
public void start()
{
//here you can call your method:runTools()
runTool();
}
}
public void runTools()
{
final String run_tool ="cmd.exe /C sources.exe";
try
{
Process tool_proc = Runtime.getRuntime().exec(run_tool);
}
catch (IOException e)
{
e.printStackTrace();
}
}
here is my main class of the programe
public class MyClassName2
{
public static void main(String[] ars)
{
Runnable *obj1=new MyClassName1();
Thread t=new Thread(obj);
t.start()
}
I hope this helps to you
精彩评论