【问题标题】:start a thread which terminates the process after a specified time启动一个线程,该线程在指定时间后终止进程
【发布时间】:2013-04-11 10:37:46
【问题描述】:

我正在为一个网络执行一个程序,在该网络中我有一定数量的任务在循环中执行,它工作正常,但是当由于网络问题而出现任何缺陷时,它会卡在任何任务中。所以我想创建一个线程,它在控制进入循环时开始,经过一些延迟后它会自行终止并继续进程。

例如-

for ( /*itearting condition */)
{
    //thread start with specified time.
    task1;
    task2;
    task3;
    //if any execution delay occur then wait till specified time and then
    //continue.
}

请给我一些关于这个的线索,sn-ps 可以帮助我很多,因为我需要尽快修复它。

【问题讨论】:

  • 从长远来看,您最好编写能够抵御网络问题的代码。

标签: java multithreading


【解决方案1】:

一个线程只能在它的合作下被终止(假设你想保存进程)。在线程的配合下,您可以使用它支持的任何终止机制来终止它。没有它的合作,它就无法完成。通常的方法是设计线程以合理地处理interrupted。如果时间过长,你可以让另一个线程中断它。

【讨论】:

  • 我希望在执行任务之前创建一个独立线程并开始重复查找时间并在指定时间自行终止。
  • 对。按照我的回答。 1)设计要终止的线程以合理地处理被中断。 2)如果时间太长,启动另一个线程来中断线程。
【解决方案2】:

我想你可能需要这样的东西:

import java.util.Date;

public class ThreadTimeTest {

    public static void taskMethod(String taskName) {
        // Sleeps for a Random amount of time, between 0 to 10 seconds
        System.out.println("Starting Task: " + taskName);
        try {
            int random = (int)(Math.random()*10);
            System.out.println("Task Completion Time: " + random + " secs");
            Thread.sleep(random * 1000);
            System.out.println("Task Complete");
        } catch(InterruptedException ex) {
            System.out.println("Thread Interrupted due to Time out");
        }
    }

    public static void main(String[] arr) {
        for(int i = 1; i <= 10; i++) {
            String task = "Task " + i;
            final Thread mainThread = Thread.currentThread();
            Thread interruptThread = new Thread() {
                public void run() {
                    long startTime = new Date().getTime();
                    try {
                        while(!isInterrupted()) {
                            long now = new Date().getTime();
                            if(now - startTime > 5000)  {
                                //Its more than 5 secs
                                mainThread.interrupt();
                                break;
                            } else
                                Thread.sleep(1000);
                        }
                    } catch(InterruptedException ex) {}
                }
            };
            interruptThread.start();
            taskMethod(task);
            interruptThread.interrupt();
        }
    }
}

【讨论】:

  • 是的,非常感谢您对问题的理解程度
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-25
  • 2014-07-12
  • 1970-01-01
  • 2011-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多