boolean
isCancelled()
Returns
true if this task was cancelled before it completed normally.
Example
import java.util.concurrent.*; import java.util.*; public class CallableTask implements Callable{ String name; CallableTask(String name){ this.name = name; } public String call(){ try{ System.out.println(name +" Started Executing"); Thread.sleep(1000); System.out.println(name +" Finishes Execution"); } catch(Exception e){ System.out.println("Task Interrupted " + e); } return (new Date() + " :: " + name); } }
import java.util.concurrent.*; import java.util.*; class SimpleThreadPool{ public static void main(String args[])throws Exception{ List<Future<String>> l1 = new ArrayList<Future<String>> (); ExecutorService exec = new ThreadPoolExecutor(3, 3, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); CallableTask task1 = new CallableTask("task1"); Future<String> f1 = exec.submit(task1); Future<String> f2 = exec.submit(task1); f1.cancel(false); f2.cancel(true); System.out.println("is the task cancelled " + f1.isCancelled()); System.out.println("is the task cancelled " + f2.isCancelled()); exec.shutdown(); } }
Output
task1 Started Executing task1 Started Executing is the task cancelled true is the task cancelled true Task Interrupted java.lang.InterruptedException: sleep interrupted task1 Finishes Execution
As
you observe the output, task1 finishes execution normally, where as
task2 thrown InterruptedException. Since f1 calls cancel with false
as argument and f2 calls cancel with true as an argument.
f1.cancel(false)
f2.cancel(true)
ExecutorService
exec = new ThreadPoolExecutor(3, 3, 0L, TimeUnit.MILLISECONDS, new
LinkedBlockingQueue<Runnable>())
Statement
creates a thread pool of 3 threads.
exec.submit(tasks)
Submit
the tasks to the thread pool. When the task is submitted, ThreadPool
assigns a thread to execute the call method of the Callable Object.
No comments:
Post a Comment