Reputation: 453
My program should run with multithreads for a really long time. I need the ability to set timeout for the threads, and once thread is terminated I want to start it again. here is my code:
@Test
public void testB() throws InterruptedException {
final ExecutorService threadPool = Executors.newFixedThreadPool(2);
for(int i=0; i<2; i++){
threadPool.submit(new Runnable() {
public void run() {
System.out.println("thread start: " + Thread.currentThread().getName());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
threadPool.shutdown();
threadPool.awaitTermination(100000, TimeUnit.SECONDS);
}
Upvotes: 0
Views: 309
Reputation: 2828
Below code will run the same to tasks over and over again. The pool will be shutdown after a given amount of time.
This seems to do what you requested.
final ExecutorService threadPool = Executors.newFixedThreadPool(2);
for(int i = 0; i < 2; i++){
final int taskNb = i;
threadPool.submit(new Runnable() {
public void run() {
System.out.println("Thread " + taskNb + " start: " + Thread.currentThread().getName());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Submit same task again
threadPool.submit(this);
}
});
}
// Only shutdown the pool after given amount of time
Thread.sleep(100_000_000);
threadPool.shutdown();
// Wait for running tasks to finish
threadPool.awaitTermination(5, TimeUnit.SECONDS);
Upvotes: 1