I wrote the code below. To run the bat file from a Java application, I use process.exec (). But the bat can hang sometime, so I need to set a timeout for this process. I start a new thread and a new process in the thread, I set the timeout in the thread and kill the thread when it is timeout. But I found that the process cannot be destroyed when a timeout occurs. So I'm confused about how to kill a thread?
Code:
StreamGobbler:
import java.util.*; import java.io.*; class StreamGobbler extends Thread { InputStream is; String type; StreamGobbler(InputStream is, String type) { this.is = is; this.type = type; } 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(); } } }
Main:
public class test { public static void main(String args[]) throws InterruptedException { Runnable r = new ShengThread(); Thread sheng = new Thread(r); sheng.start(); sheng.join(1000); if (sheng.isAlive()) { sheng.interrupt(); } if (sheng.isAlive()) { System.out.println("It is dead."); } } } class ShengThread implements Runnable { public void run() { Process proc = null; try { String osName = System.getProperty("os.name" ); String[] cmd = new String[3]; if( osName.equals( "Windows XP" ) ) { cmd[0] = "cmd" ; cmd[1] = "/C" ; cmd[2] = "c:\\status.bat"; } Runtime rt = Runtime.getRuntime(); System.out.println(osName+"Execing " + cmd[0] + " " + cmd[1] + " " + cmd[2]); try { proc = rt.exec(cmd); } catch (IOException e) {
source share