您的位置:首页 > 编程语言 > Java开发

java学习笔记 线程池的使用1

2011-05-29 21:19 501 查看
多线程编程技术已经成为现在开发人员必不可少的一项重要技能。在很多情况下可以改善程序的响应性能,提高资源的利用效率,在如今多核CPU的年代里,这些显得更为重要。
一般的,对于使用多线程的来完成指定的任务,首先我们需要创建线程对象,然后使线程执行,线程执行完毕后即会被系统垃圾回收,不能再启动执行了。再此种模式下很多时候会严重影响程序的执行性能,因为创建线程对象以及清理回收线程垃圾都会大量暂用CPU等系统资源。所以为了解决这方面的问题我们使用了线程池。
在项目的开发当中有着各种不同类型的线程池,常用的大致有以下两种:
1.固定尺寸的线程池;
2.可变尺寸的线程池;

该片文章首先简介下固定线程池的用法:
取固定线程池对象:通过Executors类的静态工厂方法来获取

public static ExecutorService newFixedThreadPool(int nThreads)
其中的nThread为线程池的尺寸。
public static ExecutorService newSingleThreadExecutor()
该方法类似于newFixedThreadPool(1),在同一时刻只可以执行一个任务。可以保证多个任务顺序执行。

上面两个静态工厂方法返回的都是对ExecutorService接口类型的引用,其实此引用指向的就是线程池对象,我们可以调用其中的execute方法来使线程池中的线程执行指定的任务。
void execute(Runnable command)
下面是一个简单的使用固定线程池的例子

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RegularThreadPool {
/**
* 对于固定线程池而言,如果需要执行的任务的数量大于线程池的尺寸,则有的任务要进入此线程池的等待队列
* @param args
*/
public static void main(String[] args) {
RegularThreadPool pool = new RegularThreadPool();
//创建尺寸为2的固定线程池
ExecutorService threadPool = Executors.newFixedThreadPool(2);
//创建三个任务对象
RegularThreadPool.MyTask mt1 = pool.new MyTask("Task1");
RegularThreadPool.MyTask mt2 = pool.new MyTask("Task2");
RegularThreadPool.MyTask mt3 = pool.new MyTask("Task3");
//启动三个任务执行
threadPool.execute(mt1);
threadPool.execute(mt2);
threadPool.execute(mt3);
threadPool.shutdown();
}

class MyTask implements Runnable {
private String name;

public MyTask(String name) {
this.name = name;
}

public void run() {
System.out.println("/n========任务" + name + "开始执行========");
for (int i = 0; i < 25; i++) {
System.out.println("[" + name + "_" + i + "] ");
}
System.out.println("/n========任务" + name + "执行结束========");
}
}
}

newSingleThreadExecutor()的使用方法于此类似,此处就不做说明了。
谢谢
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: