Attempts
to stop all actively executing tasks, halts the processing of waiting
tasks, and returns a list of the tasks that were awaiting execution.
class WorkerThread implements Runnable{ String taskName; WorkerThread(String taskName){ this.taskName = taskName; } public String toString(){ return taskName; } public void run(){ try{ Thread t1 = Thread.currentThread(); System.out.println(t1.getName() + " executing the task " + taskName); t1.sleep(1000); System.out.println(t1.getName() + " completed the task " + taskName); } catch(Exception e){ System.out.println(e); } } }
import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.*; class SimpleThreadPool{ public static void main(String args[])throws Exception{ ExecutorService exec = new ThreadPoolExecutor(3, 3, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); WorkerThread tasks[] = new WorkerThread[10]; for(int i=0; i<10; i++){ tasks[i] = new WorkerThread("task" + i); exec.execute(tasks[i]); } List<Runnable> l1 = exec.shutdownNow(); exec.awaitTermination(10, TimeUnit.SECONDS); System.out.println("Waiting Threads are "); Iterator i1 = l1.iterator(); while(i1.hasNext()){ System.out.println(i1.next()); } } }
Sample
Output
pool-1-thread-2 executing the task task1 pool-1-thread-1 executing the task task0 pool-1-thread-3 executing the task task2 java.lang.InterruptedException: sleep interrupted java.lang.InterruptedException: sleep interrupted java.lang.InterruptedException: sleep interrupted Waiting Threads are task3 task4 task5 task6 task7 task8 task9
awaitTermination()
Blocks until all tasks have completed execution after a shutdown
request, or the timeout occurs, or the current thread is interrupted,
whichever happens first.
Executor
exec = new ThreadPoolExecutor(3, 3, 0L, TimeUnit.MILLISECONDS, new
LinkedBlockingQueue<Runnable>());
Above
statement create a thread pool of size 3. So it can run 3 tasks at a
time, Since 3 threads are reside in the pool.
exec.submit(tasks[i])
Submit
the tasks to the thread pool. When the task is submitted, ThreadPool
assigns a thread to execute the run method of the Runnable Object.
No comments:
Post a Comment