0

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

例如-

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

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

4

2 回答 2

1

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

于 2013-04-11T10:41:22.237 回答
0

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

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();
        }
    }
}
于 2013-04-11T11:36:30.117 回答