Tag:runnable ack shutdown Execution ted run block run method executor
Package Cn.itcast.heima2;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import Java.util.concurrent.timeunit;public class Threadpooltest {/** * @param args */public static void main (string[] args) { Thread pool customization can only execute 3 threads at a time executorservice ThreadPool = Executors.newfixedthreadpool (3); The cache thread pool can dynamically change the number of threads that can be executed concurrently as needed//executorservice ThreadPool = Executors.newcachedthreadpool (); Single thread pool thread death Auto-start another threads to ensure thread pool threads are running//executorservice threadPool = Executors.newsinglethreadexecutor (); for (int i=1;i<=10;i++) {Final int task = i, Threadpool.execute (new Runnable () {@Override public void run () {for (int j= 1;j<=10;j++) {try {thread.sleep ()} catch (Interruptedexception e) {//TODO auto-generated catch block E.printstac Ktrace (); } System.out.println (/*thread.currentthread (). GetName () + "of" +*/"task" + task + "has loop" + j + "Times");}}); }//The above code although let the thread start but each thread's Run method executes at the same time the following code also executes at the same time//if the Shutdownnow () method is called at this time, it is likely to let the execution of half of the Run method stop to run the Times line Wenwen interrupted error//threaDpool.shutdownnow (); Instead, call the secondary method when all threads are idle to close the thread pool Threadpool.shutdown (); System.out.println ("All of the ten tasks have committed!"); Timer 6s after performing each 2s execution once the disadvantage can only be customized a few seconds later to use the target time minus the time realized Executors.newscheduledthreadpool (3). Scheduleatfixedrate (New Runnable () {public void run () {System.out.println ("bombing!");}},6,2,timeunit.seconds); }}
3 Thread Pools