Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
689 views
in Technique[技术] by (71.8m points)

java - Stop an infinite loop in an ExecutorService task

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

class Task implements Callable<String> {
    public String call() throws Exception {
        String s = "initial";
        try {
            System.out.println("Started..");
            /*for (int i=0;i<10000;i++) {
                if (i % 2 == 0) {
                    System.out.println("Even");
                }
            }*/
            boolean flag = true;
            while(flag) {

            }
            System.out.println("Finished!");
            s = "Done";
        }
        catch (RuntimeException e) {
            s = "RuntimeException";
        }
        catch (Exception e) {
            s = "Exception";
        }
        finally {

        }
        return s;
    }
}

public class ExecutorServiceTest {

    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        List<Future<String>> result = executor.invokeAll(Arrays.asList(new Task()), 5, TimeUnit.SECONDS);
        executor.shutdown();
        Iterator<Future<String>> iter = result.iterator();
        while (iter.hasNext()) {
            System.out.println("Came here");
            Future<String> fut = iter.next();
            System.out.println(fut.get());
        }
    }
}

Is there a way in which i can stop the thread executing the infinite loop?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes, you can replace flag (or logically &&) with !Thread.currentThread().isInterrupted().

This way, when the task is canceled, the loop will be terminated.

The loop would look something like this:

while(!Thread.currentThread().isInterrupted() && flag) {
  /* Do work. */
}

Use should be something like this:

ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> task = executor.submit(new Task());
String str;
try {
  str = task.get(5, TimeUnit.SECONDS);
} finally {
  task.cancel(true);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...