JAVA线程池
背景:系统启动一个线程的成本是比较高的,因为它涉及到与操作系统交互。在这种情况下,使用线程池可以很好地提高性能,尤其是当程序中需要创建大量生存期很短暂的线程时,更应该考虑使用线程池
原理:线程池在系统启动时就创建大量空闲线程,程序将一个Runnable对象传给线程池,线程池将会启动一条线程来执行该对象的run方法,当run方法执行结束后,该线程并不会死亡,而是再次返回线程池中成为空闲状态,等待执行下一个Runnable对象的run方法;此外,使用线程池可以有效控制系统中的并发线程的数量
使用线程池来执行线程任务的步骤如下:
(1)调用Executors类的静态工厂方法创建一个ExecutorService对象,该对象代表一个线程池
(2)创建Runnable实现类 或 Callable实现类的实例,作为线程执行任务
(3)调用ExecutorService对象的submit方法来提交Runnable实例或Callable实例
(4)当不想提交任何任务时调用ExecutorService对象的shutdown方法来关闭线程池
例子:
1 import java.util.concurrent.ExecutorService; 2 import java.util.concurrent.Executors; 3 4 class ThreadTest implements Runnable { 5 public void run() { 6 for (int i=0; i<100; i++) { 7 System.out.println(Thread.currentThread().getName() + "的i的值为:" + i); 8 } 9 } 10 } 11 12 public class ThreadPoolTest { 13 public static void main(String[] args) { 14 ExecutorService pool = Executors.newFixedThreadPool(6); 15 pool.submit(new ThreadTest()); 16 pool.submit(new ThreadTest()); 17 /* 18 ThreadTest t1 = new ThreadTest(); 19 new Thread(t1).start(); 20 ThreadTest t2 = new ThreadTest(); 21 new Thread(t2).start(); 22 */ 23 pool.shutdown(); 24 } 25 }
执行结果为:
D:\聚划算\技术部\编程练习\Thread\ThradPoolTest>java ThreadPoolTest
pool-1-thread-1的i的值为:0
pool-1-thread-2的i的值为:0
pool-1-thread-1的i的值为:1
pool-1-thread-2的i的值为:1
pool-1-thread-1的i的值为:2
pool-1-thread-1的i的值为:3
pool-1-thread-1的i的值为:4
pool-1-thread-1的i的值为:5
pool-1-thread-1的i的值为:6
pool-1-thread-1的i的值为:7
pool-1-thread-1的i的值为:8 *****
例子2:
1 package threadpool.ThreadFactory; 2 3 import java.util.concurrent.ExecutorService; 4 import java.util.concurrent.Executors; 5 import java.util.concurrent.ThreadFactory; 6 7 8 public class TestThreadFactory { 9 private static String consumerThreadName="consumerThread"; 10 11 public static void main(String[] args) { 12 ExecutorService executor=Executors.newSingleThreadExecutor(new ThreadFactory() { 13 14 @Override 15 public Thread newThread(Runnable r) { 16 // TODO Auto-generated method stub 17 return new Thread(r, consumerThreadName); 18 } 19 }); 20 executor.execute(new ConsumeRunnable()); 21 22 } 23 } 24 25 class ConsumeRunnable implements Runnable { 26 27 @Override 28 public void run() { 29 // TODO Auto-generated method stub 30 System.out.println(Thread.currentThread().getName() + "正在运行..."); 31 32 try { 33 Thread.sleep(1000); 34 } catch (InterruptedException e) { 35 // TODO Auto-generated catch block 36 e.printStackTrace(); 37 } 38 } 39 40 }
这里线程工厂的好处就是可以自己定义线程的名字。
Interface ExecutorService
- All Superinterfaces:
- Executor
- All Known Subinterfaces:
- ScheduledExecutorService
- All Known Implementing Classes:
- AbstractExecutorService, ForkJoinPool, ScheduledThreadPoolExecutor, ThreadPoolExecutor
public interface ExecutorService extends Executor
AnExecutor
that provides methods to manage termination and methods that can produce aFuture
for tracking progress of one or more asynchronous tasks.An ExecutorService can be shut down, which will cause it to reject new tasks. Two different methods are provided for shutting down an ExecutorService. The
shutdown()
method will allow previously submitted tasks to execute before terminating, while theshutdownNow()
method prevents waiting tasks from starting and attempts to stop currently executing tasks. Upon termination, an executor has no tasks actively executing, no tasks awaiting execution, and no new tasks can be submitted. An unused ExecutorService should be shut down to allow reclamation of its resources.Method submit extends base method
Executor.execute(java.lang.Runnable)
by creating and returning aFuture
that can be used to cancel execution and/or wait for completion. Methods invokeAny andinvokeAll perform the most commonly useful forms of bulk execution, executing a collection of tasks and then waiting for at least one, or all, to complete. (ClassExecutorCompletionService
can be used to write customized variants of these methods.)The
Executors
class provides factory methods for the executor services provided in this package.
Class Executors
- java.lang.Object
- java.util.concurrent.Executors
public class Executors extends Object
Factory and utility methods forExecutor
,ExecutorService
,ScheduledExecutorService
,ThreadFactory
, andCallable
classes defined in this package. This class supports the following kinds of methods:- Methods that create and return an
ExecutorService
set up with commonly useful configuration settings. - Methods that create and return a
ScheduledExecutorService
set up with commonly useful configuration settings. - Methods that create and return a "wrapped" ExecutorService, that disables reconfiguration by making implementation-specific methods inaccessible.
- Methods that create and return a
ThreadFactory
that sets newly created threads to a known state. - Methods that create and return a
Callable
out of other closure-like forms, so they can be used in execution methods requiring Callable.
- Since:
- 1.5
- Methods that create and return an
Interface ThreadFactory
public interface ThreadFactory
An object that creates new threads on demand. Using thread factories removes hardwiring of calls tonew Thread
, enabling applications to use special thread subclasses, priorities, etc.The simplest implementation of this interface is just:
class SimpleThreadFactory implements ThreadFactory { public Thread newThread(Runnable r) { return new Thread(r); } }
TheExecutors.defaultThreadFactory()
method provides a more useful simple implementation, that sets the created thread context to known values before returning it.- Since:
- 1.5