在java中一段时间​​后杀死进程

时间:2016-06-10 07:38:19

标签: java multithreading http

我想在一段时间后终止某个进程,如果该进程不响应 我使用此代码,但我无法实现相同的

 long start = System.currentTimeMillis(); long end = start +60000;

 1 while (System.currentTimeMillis() < end)
 2                {                 
 3                   Connection.execute(function); // execute 
 4                   break; // break if response came                    
 5                }

 6 if(System.currentTimeMillis() > end)    
 7 { 
 8 close connection;  // close connection if line no 3 will not responded 
 9 }

请帮助我同样的

2 个答案:

答案 0 :(得分:0)

由于调用Connection.execute()被阻塞,所以主线程将被阻塞直到它执行,所以在那种情况下,如果我们想在主线程被阻塞时关闭连接,我们必须关闭其他一些连接线。也许我们可以使用Timer&amp;在这种情况下TimerTask。我试着编写如下代码,也许你可以这样做。

        Timer timer = new Timer();
        while (System.currentTimeMillis() < end) {   //In any case, this loop runs for only one time, then we can replace it with IF condition
            CloseConnectionTask task = new CloseConnectionTask(Connection);
            timer.schedule(task, end); // Task will be excuted after the delay by "end" milliseconds
            Connection.execute(function); // execute
            task.cancel();  //If the excute() call returns within time ie. "end" milliseconds, then timerTask will not get executed.
            break; // break if response came//
        }
        timer.cancel(); // If you have no more scheduling tasks, then timer thread should be stopped.

下面是TimerTask实现:

class CloseConnectionTask extends TimerTask {
    private Connection con;

    public CloseConnectionTask(Connection con) {
        this.con = con;
    }
    @Override
    public void run() {
        try {
            con.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

注意:我还有一件事要说,在你的while循环中,如果调用Connection.execute()成功,那么你就从循环中断。所以我观察到的,无论如何你的循环只执行一次,如果是这种情况,那么你应该使用IF(再次是我在提供的代码中看到的,你的要求可能会有所不同)。希望它可以帮到你。如果您对此有其他想法,请分享。我的回答是基于link这个好信息。在那里。

答案 1 :(得分:-2)

这种方式无济于事 我认为你应该实现线程来实现

相关问题