线程池

什么是线程池。
线程池,其实就是一个容纳多个线程的容器,其中的线程可以反复使用,省去了频繁创建线程对象的操作,无需反复创建线程而消耗过多资源。

为什么要使用线程池。
在java中,如果每个请求到达就创建一个新线程,开销是相当大的。在实际使用中,创建和销毁线程花费的时间和消耗的系统资源都相当大,甚至可能要比在处理实际的用户请求的时间和资源要多的多。除了创建和销毁线程的开销之外,活动的线程也需要消耗系统资源。如果在一个jvm里创建太多的线程,可能会使系统由于过度消耗内存或“切换过度”而导致系统资源不足。为了防止资源不足,需要采取一些办法来限制任何给定时刻处理的请求数目,尽可能减少创建和销毁线程的次数,特别是一些资源耗费比较大的线程的创建和销毁,尽量利用已有对象来进行服务。
线程池主要用来解决线程生命周期开销问题和资源不足问题。通过对多个任务重复使用线程,线程创建的开销就被分摊到了多个任务上了,而且由于在请求到达时线程已经存在,所以消除了线程创建所带来的延迟。这样,就可以立即为请求服务,使用应用程序响应更快。另外,通过适当的调整线程中的线程数目可以防止出现资源不足的情况。

使用线程池方式--Runnable接口
通常,线程池都是通过线程池工厂创建,再调用线程池中的方法获取线程,再通过线程去执行任务方法。

Executors:线程池创建工厂类
public static ExecutorService newFixedThreadPool(int nThreads):返回线程池对象
ExecutorService:线程池类
Future<?> submit(Runnable task):获取线程池中的某一个线程对象,并执行
Future接口:用来记录线程任务执行完毕后产生的结果。线程池创建与使用

使用线程池中线程对象的步骤:
创建线程池对象
创建Runnable接口子类对象
提交Runnable接口子类对象
关闭线程池

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

public class Chi {
    public static void main(String[] args) {
        /*没有线程池的写法
        Runnable r = new MyRunnable();
        Thread t = new Thread(r);
        t.start();*/

ExecutorService e =Executors.newFixedThreadPool(2);//创建一个包含两个线程的线程池
        Runnable r = new MyRunnable();
        e.submit(r);//获取线程池中的某一个线程对象,然后调用runnable接口中的run方法
        e.submit(r);
        e.submit(r);
        e.submit(r);//注意run方法运行完,线程中的线程并不消耗,而是归还到池中
        e.shutdown();
    }
    }
    class MyRunnable implements Runnable{
@Override
    public void run() {
        System.out.println("给我一个线程:"+Thread.currentThread().getName());
        try {
            System.out.println("线程开始消耗资源"+Thread.currentThread().getName());
            Thread.sleep(2000);
            System.out.println("线程使用完毕"+Thread.currentThread().getName());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("归还到线程池中"+Thread.currentThread().getName());
    }
    }

运行结果:

给我一个线程:pool-1-thread-1
给我一个线程:pool-1-thread-2
线程开始消耗资源pool-1-thread-1
线程开始消耗资源pool-1-thread-2
线程使用完毕pool-1-thread-2
归还到线程池中pool-1-thread-2
给我一个线程:pool-1-thread-2
线程开始消耗资源pool-1-thread-2
线程使用完毕pool-1-thread-1
归还到线程池中pool-1-thread-1
给我一个线程:pool-1-thread-1
线程开始消耗资源pool-1-thread-1
线程使用完毕pool-1-thread-1
归还到线程池中pool-1-thread-1
线程使用完毕pool-1-thread-2
归还到线程池中pool-1-thread-2

使用线程池方式—Callable接口
Callable接口:与Runnable接口功能相似,用来指定线程的任务。其中的call()方法,用来返回线程任务执行完毕后的结果,call方法可抛出异常。
ExecutorService:线程池类
<T> Future<T> submit(Callable<T> task):获取线程池中的某一个线程对象,并执行线程中的call()方法
V get() 获取Future对象中封装的数据结果
Future接口:用来记录线程任务执行完毕后产生的结果。线程池创建与使用

使用线程池中线程对象的步骤:
创建线程池对象
创建Callable接口子类对象
提交Callable接口子类对象
关闭线程池

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class chi1 {
    public static void main(String[] args) {
        try{

        //MyCallable my=new MyCallable(1,1);
        //  FutureTask<Integer> ft = new FutureTask<Integer>(my);
//new Thread(ft,"有返回值的线程").start();    
    //      Integer integer = ft.get();
        //   System.out.println("子线程的返回值:"+integer);

            //创建线程池对象
            ExecutorService threadPool = Executors.newFixedThreadPool(2);
            //创建一个Callable接口子类对象
            MyCallable c = new MyCallable(100, 200);
            MyCallable c2 = new MyCallable(10, 20);
            //获取线程池中的线程,调用Callable接口子类对象中的call()方法, 完成求和操作
            Future<Integer> result = threadPool.submit(c);
            //此 Future 的 get 方法所返回的结果类型
            Integer sum= result.get();
            System.out.println("sum=" + sum);
            Future<Integer> result1 = threadPool.submit(c2);
            Integer sum1 =  result1.get();
            System.out.println("sum1=" + sum1);
            Future<Integer> result2 = threadPool.submit(c2);
            Integer sum2 =  result2.get();
            System.out.println("sum2=" + sum2);
            Future<Integer> result3 = threadPool.submit(c2);
            Integer sum3 =  result3.get();
            System.out.println("sum3=" + sum3);
            } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
    }
class MyCallable implements Callable<Integer>{
    //成员变量
    int x = 5;
    int y = 3;
    //构造方法
    public MyCallable(int x, int y){
        this.x = x;
        this.y = y;
    }
    @Override
    public Integer call() throws Exception {
        System.out.println("给我一个线程"+Thread.currentThread().getName());
        System.out.println("线程开始消耗资源"+Thread.currentThread().getName());
        Thread.sleep(2000);
        System.out.println("线程使用完毕"+Thread.currentThread().getName());
        System.out.println("归还到线程池中"+Thread.currentThread().getName());
        return x+y;
    }   
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章