线程池介绍
2016-07-17 15:45
190 查看
线程池主要干什么的呢?
线程池主要为了节省系统的资源的,为什么这么说呢,因为当有线程任务的时候,就从线程池中拿一个,用完了在放回去,这样就避免了重复创建线程从而带来系统性能的开销。
线程池的基本思想
线程池的基本思想就是一种对象池的思想,说白了就是开辟一块内存空间,然后new适当的线程对象,然后将对象放在池子里面,用的时候从池子里面拿,用完了在还回去。
如何创建一个线程池?
线程池分两种:一种是固定尺寸的线程池,一种是可变尺寸的线程池。
固定尺寸的线程池:
package com.lilei; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class TestExcutor { public static void main(String[] args) { //创建一个可重用固定线程数的线程池,以共享的无界队列方式来运行这些线程。 ExecutorService pool = Executors.newFixedThreadPool(2); MyThread1 th1 = new MyThread1(); MyThread1 th2 = new MyThread1(); MyThread1 th3 = new MyThread1(); MyThread1 th4 = new MyThread1(); MyThread1 th5 = new MyThread1(); //将线程放入到线程池中执行 pool.execute(th1); pool.execute(th2); pool.execute(th3); pool.execute(th4); pool.execute(th5); } } class MyThread1 extends Thread{ @Override public void run() { System.out.println(Thread.currentThread().getName()+"正在执行......"); } }
固定尺寸的线程池还有一种单任务线程池,只要改动上面一个小小的地方,就是 将
ExecutorService pool = Executors.newFixedThreadPool(2);改成`ExecutorService pool = Executors.newSingleThreadExecutor();
可变尺寸的线程池,其实也只是改一行代码就行了,和单任务线程池一样改成
ExecutorService pool = Executors.newCachedThreadPool();这个样子就ok了,是不是很简单。
延迟连接池,也是改动上面那个例子的代码,例子如下:
package com.lilei; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class TestExcutor { public static void main(String[] args) { //创建一个可重用固定线程数的线程池,以共享的无界队列方式来运行这些线程。 //ExecutorService pool = Executors.newFixedThreadPool(2); ScheduledExecutorService pool = Executors.newScheduledThreadPool(2); MyThread1 th1 = new MyThread1(); MyThread1 th2 = new MyThread1(); MyThread1 th3 = new MyThread1(); MyThread1 th4 = new MyThread1(); MyThread1 th5 = new MyThread1(); //将线程放入到线程池中执行 pool.execute(th1); pool.execute(th2); pool.execute(th3); // pool.execute(th4); // pool.execute(th5); pool.schedule(th4, 10, TimeUnit.SECONDS);// thread time seconds pool.schedule(th5, 10, TimeUnit.SECONDS); } } class MyThread1 extends Thread{ @Override public void run() { System.out.println(Thread.currentThread().getName()+"正在执行......"); } }
并没有重新写一个例子,而是在固定线程池的例子上改的,仅仅需要改动其中几行代码。其实固定尺寸和可变尺寸的线程就只有new出来的线程池对象不同,其他的好像没什么区别。
还有一个单任务延迟线程池和自定义线程池其实一样的,也差不多,有兴趣的可以看看jdk文档。上面有很详细的介绍。
相关文章推荐
- C#线程间不能调用剪切板的解决方法
- C#多线程学习之(四)使用线程池进行多线程的自动管理
- C#线程同步的三类情景分析
- C#获取进程或线程相关信息的方法
- 简单对比C#程序中的单线程与多线程设计
- C#停止线程的方法
- C#子线程更新UI控件的方法实例总结
- C#线程队列用法实例分析
- C++使用CriticalSection实现线程同步实例
- c++线程池实现方法
- 基于C++实现的线程休眠代码
- C语言实现支持动态拓展和销毁的线程池
- c++实现简单的线程池
- VB读取线程、句柄及写入内存的API代码实例
- C#网络编程基础之进程和线程详解
- C#通过Semaphore类控制线程队列的方法
- C#多线程处理多个队列数据的方法
- C#实现线程安全的简易日志记录方法
- C#中线程同步对象的方法分析
- ASP.NET线程相关配置