我正在运行无限循环,需要完成以下步骤:
我已经研究了将来的带有超时参数的get API,但这并不是本质上的阻塞。
while(any thread available in thread pool){
Task task = fetchTask();
// somehow execute this task in a non-blocking fashion with a timeout.
}
是否有一种方法可以在超时后杀死异步执行的线程?超时后,线程执行将停止并释放资源吗?
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);