安排任务执行,但不要阻止调用者

Schedule task execution, but don't block callers

安排要执行的任务但不阻塞调用线程的正确方法是什么。

这样做正确吗?

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class Main {

    public static void main(String [] args) throws ExecutionException, InterruptedException {
        final ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();

        ScheduledFuture<?> f = service.schedule(new Runnable() {
            public void run() {
                System.out.println("Before sleep");
                try {
                    Thread.sleep(50000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("After sleep");
            }
        }, 0, TimeUnit.MINUTES);

        try {
            f.get(0, TimeUnit.MINUTES);
        } catch (TimeoutException e) {
            //
        }


        System.out.println("Main thread");
    }
}

据我所知,如果我只调用 f.get(),那么它会阻塞调用线程直到 future 完成。我要做的是提交任务,但不要阻塞调用者线程。

调用f.get()只会在任务尚未完成时阻塞。如果任务完成,它将 return 它的结果而不会阻塞。

如果您不关心结果而只想运行一些任务,只需忽略 Future return 由 schedule() 编辑的内容。