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 に答える