如何在Java 8中超时后杀死异步运行的线程及其含义

问题描述 投票:1回答:1

我正在运行无限循环,需要完成以下步骤:

  1. 检查执行程序服务中的可用线程(无限循环)
  2. 在循环中获取任务。
  3. 在后台执行任务(非阻塞),并且如果花费3秒以上的时间,则杀死执行任务的线程。

我已经研究了将来的带有超时参数的get API,但这并不是本质上的阻塞。

while(any thread available in thread pool){

Task task = fetchTask();

// somehow execute this task in a non-blocking fashion with a timeout.


}

是否有一种方法可以在超时后杀死异步执行的线程?超时后,线程执行将停止并释放资源吗?

java multithreading asynchronous java-8
1个回答
0
投票
To achieve this behavior you need this :

 1. Custom class that extends the Thread class or implements the Runnable interface
 3. use a Thread Executor to simply have asynchronous threads 

The Custom class let as named it 'Task' can have a special implemetation 

public class Task   implements Runnable {

     private String name;

        public Task(String name) {
            this.name = name;
        }

        public String getName() {
            return name;`enter code here`
        }

        public void run() {
            int startTimeInSeconds = new Date().getSeconds();
            System.out.println("Executing : " + name + ", Current Seconds : " + new Date().getSeconds());
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            int endTimeInSeconds = new Date().getSeconds();
            if(endTimeInSeconds - startTimeInSeconds > 3 ) 
                System.out.println("The Task named " + name + " has been shutted down unexpectedly after 3 seconds!");

        }

}

Inside your Main class 
//Declaration of an executor and limitation of number of threads to execute
final int numberOfThreads = 3;
ScheduledThreadPoolExecutor executor = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(numberOfThreads );

//Initantiate 'Task' class ( here you can change it by doing your own staffs as fetching in the thread pool)
        Task  t1 = new Task("Task1");
        Task  t2 = new Task("Task2");
        Task  t3 = new Task("Task3");

    System.out.println("Tasks has been initiated !");
//The execution of threads asynchronously
        executor.execute(t1);
        executor.execute(t2);
        executor.execute(t3);
© www.soinside.com 2019 - 2024. All rights reserved.