Remove task from ExecutorService

package prakshar.executorservice;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ExecutorServiceRemove {

	static ExecutorService executorService = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS,
			new LinkedBlockingQueue<Runnable>());
	static List<Integer> removeTaskList = new ArrayList<>();

	public static void main(String arg[]) {

		executorService.execute(() -> (new Task(1)).method());
		executorService.execute(() -> (new Task(2)).method());
		executorService.execute(() -> (new Task(3)).method());
		removeTaskList.add(Integer.parseInt("3"));
		System.out.println("Done");
	}
}

class Task {

	Integer i;

	public Task(Integer i) {
		this.i = i;
	}

	public void method() {
		try {
			if (ExecutorServiceRemove.removeTaskList.contains(i)) {
				ExecutorServiceRemove.removeTaskList.remove(i);
				return;
			}
			System.out.println(i);
			TimeUnit.MILLISECONDS.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

(Visited 15 times, 1 visits today)

PrAkAsH

Eyeing investment. Please note that the views given in this website are meant for reference and guidance of the readers to explore further on the topics and take informed decisions. These should not be construed as investment advice or legal opinion.

You may also like...

Leave a Reply

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

Solve : *
24 − 15 =