在java中一段时间后终止进程

在java中一段时间后终止进程,java,multithreading,http,Java,Multithreading,Http,如果某个进程没有响应,我想在一段时间后终止该进程 我使用了这个代码,但我不能达到同样的效果 long start = System.currentTimeMillis(); long end = start +60000; 1 while (System.currentTimeMillis() < end) 2 { 3 Connection.execute(function); /

如果某个进程没有响应,我想在一段时间后终止该进程 我使用了这个代码,但我不能达到同样的效果

 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 }
long start=System.currentTimeMillis();长端=起点+60000;
1 while(System.currentTimeMillis()结束)
7 { 
8关闭连接;//如果第3行没有响应,则关闭连接
9 }
请同样帮助我

这样做没有帮助
 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 }

我认为您应该实现线程来实现这一点,因为调用连接。execute()被阻塞,所以主线程将被阻塞,直到它执行为止,因此在这种情况下,如果我们想在主线程被阻塞时关闭连接,我们必须关闭其他线程中的连接。也许我们可以在这种情况下使用定时器和定时器任务。我试着写一些代码如下,也许你可以这样做

        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.

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

3号线的电话是否阻塞?如果是,那么我认为在控件从调用连接返回之前不会执行第8行。执行(函数)。是的,您是对的,但如果第3行阻塞,则需要在特定时间后关闭。在这种情况下,您是否有其他具有定时等待的重载API。我的意思是这样说-Connection.execute(函数,waitingTime);在这种情况下,我认为我们必须使用其他线程来关闭连接,因为主线程在第3行被阻塞。我试着为它写一些解决方案,也许它能帮助你。