java.util.concurrent 包含许多线程安全、测试良好、高性能的并发构建块。创建 java.util.concurrent 的目的就是要实现 Collection 框架对数据结构所执行的并发操作。通过提供一组可靠的、高性能并发构建块,开发人员可以提高并发类的线程安全、可伸缩性、性能、可读性和可靠性。
这里面主要研究 java.util.concurrent 中的高级实用程序类 -- 线程安全集合、线程池、信号和同步工具。
对于线程池的研究,看一下下面的例子:
package com.davint.poolthread;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
/**
* 线程池示例
* @version 1.0
* @author Davint
* @see
*/
public class ThreadPool extends Thread {
/**
* main()
*/
public static void main(String args[]){
//在这里创建一个可重用固定线程数的线程池
ExecutorService pool =Executors.newFixedThreadPool(2);
//创建实现Runnable接口对象,Thread对象也是要实现Runnable接口
Thread t1= new MyThread();
Thread t2= new MyThread();
Thread t3= new MyThread();
Thread t4= new MyThread();
Thread t5= new MyThread();
Thread t6= new MyThread();
Thread t7= new MyThread();
//将线程放入池中进行执行操作
pool.execute(t1);
pool.execute(t2);
pool.execute(t3);
pool.execute(t4);
pool.execute(t5);
pool.execute(t6);
pool.execute(t7);
//关闭线程池
pool.shutdown();
}
}
class MyThread extends Thread{
public void run(){
System.out.println(Thread.currentThread().getName()+"正在执行..."+Thread.currentThread().getId());
}
}