Executor接口,用来管理Runnable对象的执行,Executor对象创建并管理一组Runnable对象的线程,这组线程就做线程池(thread pool).优点是Executor对象能复用了已经有的线程,减少为每个任务创建新线程的开销,提高性能,它能通过优化线程的数量,提高程序性能,保证处理器一直处于忙碌状,而不必创建过多的线程使程序资源耗尽。
具体的做法如下:
1 声明一个execute()方法,接收一个Runnable实参,
2
3
- import java.util.concurrent.Executors;
- import java.util.concurrent.ExecutorService;
- public class TaskExecutor
- {
- public static void main( String[] args )
- {
- // create and name each runnable
- PrintTask task1 = new PrintTask( "task1" ); //runnable对象
- PrintTask task2 = new PrintTask( "task2" );
- PrintTask task3 = new PrintTask( "task3" );
- System.out.println( "Starting Executor" );
- // create ExecutorService to manage threads
- ExecutorService threadExecutor = Executors.newCachedThreadPool();
- // start threads and place in runnable state
- threadExecutor.execute( task1 ); // start task1
- threadExecutor.execute( task2 ); // start task2
- threadExecutor.execute( task3 ); // start task3
- // shut down worker threads when their tasks complete
- threadExecutor.shutdown();
- System.out.println( "Tasks started, main ends.\n" );
- } // end main
- } // end class TaskExecutor