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 38 times, 1 visits today)

Leave a Reply

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

Solve : *
14 + 1 =