How to automatically close a Java thread when it times out?

In Java, you can use ExecutorService to control the timeout of threads and automatically close them. Here is an example code:

import java.util.concurrent.*;

public class ThreadTimeoutExample {

    public static void main(String[] args) {
        ExecutorService executor = Executors.newSingleThreadExecutor();

        try {
            Future<String> future = executor.submit(new Callable<String>() {
                @Override
                public String call() throws Exception {
                    // 在这里执行耗时操作
                    Thread.sleep(5000);
                    return "Task completed";
                }
            });

            try {
                String result = future.get(3, TimeUnit.SECONDS); // 设置超时时间为3秒
                System.out.println(result);
            } catch (TimeoutException e) {
                System.out.println("Task timed out and will be cancelled");
                future.cancel(true); // 取消任务
            }
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        } finally {
            executor.shutdown();
        }
    }
}

In the example above, we created a single-threaded pool using ExecutorService and submitted a task that takes 5 seconds to complete. By setting a timeout of 3 seconds using the get method of Future, the task will be canceled and a TimeoutException will be thrown if it is not completed within the specified time. Don’t forget to call the shutdown method of ExecutorService to close the thread pool.

 

More tutorials

What are the methods for handling timeouts in Java?(Opens in a new browser tab)

Reading and Writing data using Python(Opens in a new browser tab)

What is the future direction of development for the Cacti system?(Opens in a new browser tab)

Java Thread Join method(Opens in a new browser tab)

How can you implement throwable to exception in Java?(Opens in a new browser tab)

 

Leave a Reply 0

Your email address will not be published. Required fields are marked *