码迷,mamicode.com
首页 > 编程语言 > 详细

java 创建线程池的4中方式

时间:2018-03-17 14:20:24      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:java 创建线程池的4中方式

Java线程池使用说明

线程池的作用:
线程池作用就是限制系统中执行线程的数量。
根据系统的环境情况,可以自动或手动设置线程数量,达到运行的最佳效果;少了浪费了系统资源,多了造成系统拥挤效率不高。用线程池控制线程数量,其他线程排队等候。一个任务执行完毕,再从队列的中取最前面的任务开始执行。若队列中没有等待进程,线程池的这一资源处于等待。当一个新任务需要运行时,如果线程池中有等待的工作线程,就可以开始运行了;否则进入等待队列。

java中常用线程池

  1. newSingleThreadExecutor
    创建一个单线程的线程池。这个线程池只有一个线程在工作,也就是相当于单线程串行执行所有任务。如果这个唯一的线程因为异常结束,那么会有一个新的线程来替代它。此线程池保证所有任务的执行顺序按照任务的提交顺序执行。
    2.newFixedThreadPool
    创建固定大小的线程池。每次提交一个任务就从线程池中拿一个线程,直到线程达到线程池的最大大小。线程池的大小一旦达到最大值就会保持不变,如果某个线程因为执行异常而结束,那么线程池会补充一个新线程。
    1. newCachedThreadPool
      创建一个可缓存的线程池。如果线程池的大小超过了处理任务所需要的线程,
      那么就会回收部分空闲(60秒不执行任务)的线程,当任务数增加时,此线程池又可以智能的添加新线程来处理任务。此线程池不会对线程池大小做限制,线程池大小完全依赖于操作系统(或者说JVM)能够创建的最大线程大小。
      4.newScheduledThreadPool
      创建一个支持定时以及周期性执行任务的线程池。多数情况下可用来替代Timer类

单线程线程池 Executors.newSingleThreadExecutor()

import java.util.concurrent.Callable;
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.newSingleThreadExecutor();//创建一个单线程的线程池
        e.submit(new MyRunnable());
        e.submit(new MyRunnable());
        e.submit(new MyRunnable());
        e.submit(new MyRunnable());
        e.submit(new MyRunnable());
        e.submit(new MyRunnable());
        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-1
线程使用完毕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-1
线程开始消耗资源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-1
给我一个线程: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-1
归还到线程池中pool-1-thread-1

创建一个固定长度的线程池 Executors.newFixedThreadPool()

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-1
归还到线程池中pool-1-thread-1
线程使用完毕pool-1-thread-2
给我一个线程:pool-1-thread-1
线程开始消耗资源pool-1-thread-1
归还到线程池中pool-1-thread-2
给我一个线程:pool-1-thread-2
线程开始消耗资源pool-1-thread-2
线程使用完毕pool-1-thread-1
归还到线程池中pool-1-thread-1
线程使用完毕pool-1-thread-2
归还到线程池中pool-1-thread-2

创建一个可缓存的线程池

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.newCachedThreadPool();
        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-4
给我一个线程:pool-1-thread-3
给我一个线程:pool-1-thread-2
线程开始消耗资源pool-1-thread-3
线程开始消耗资源pool-1-thread-4
线程开始消耗资源pool-1-thread-1
线程开始消耗资源pool-1-thread-2
线程使用完毕pool-1-thread-2
线程使用完毕pool-1-thread-3
线程使用完毕pool-1-thread-4
线程使用完毕pool-1-thread-1
归还到线程池中pool-1-thread-4
归还到线程池中pool-1-thread-2
归还到线程池中pool-1-thread-3
归还到线程池中pool-1-thread-1

创建一个可缓存并且可以周期性执行任务的线程池

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Chi {
    public static void main(String[] args) {
        /*没有线程池的写法
        Runnable r = new MyRunnable();
        Thread t = new Thread(r);
        t.start();*/
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ScheduledThreadPoolExecutor e = new ScheduledThreadPoolExecutor(3);//参数表示线程容量
        System.out.println(simpleDateFormat.format(new Date()));
        // 但是如果执行任务时间大约2s则不会并发执行后续任务将会延迟。
        ScheduledFuture<?> resultFuture = e.scheduleAtFixedRate(new MyRunnable(), 0, 2000, TimeUnit.MILLISECONDS);//第一个参数任务,第二个参数表示执行任务前等待的时间,第三个参数表示任务启动间隔时间,第四参数表示时间单位
        e.scheduleAtFixedRate(new MyRunnable1(), 0, 2000, TimeUnit.MILLISECONDS);//第一个参数任务,第二个参数表示执行任务前等待的时间,第三个参数表示任务启动间隔时间,第四参数表示时间单位
        // // 由于是定时任务,一直不会返回
        //Object object = resultFuture.get();
    }
}

class MyRunnable implements Runnable{
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"给我一个线程:"+simpleDateFormat.format(new Date()));
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
class MyRunnable1 implements Runnable{
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"给我一个线程1:"+simpleDateFormat.format(new Date()));
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

运行结果
2018-03-17 13:48:05
pool-1-thread-1给我一个线程:2018-03-17 13:48:05
pool-1-thread-2给我一个线程1:2018-03-17 13:48:05
pool-1-thread-1给我一个线程:2018-03-17 13:48:07
pool-1-thread-1给我一个线程:2018-03-17 13:48:09
pool-1-thread-3给我一个线程:2018-03-17 13:48:11
pool-1-thread-3给我一个线程:2018-03-17 13:48:13
pool-1-thread-2给我一个线程1:2018-03-17 13:48:15
pool-1-thread-3给我一个线程:2018-03-17 13:48:15
pool-1-thread-3给我一个线程:2018-03-17 13:48:17
pool-1-thread-3给我一个线程:2018-03-17 13:48:19
pool-1-thread-1给我一个线程:2018-03-17 13:48:21
pool-1-thread-1给我一个线程:2018-03-17 13:48:23
pool-1-thread-3给我一个线程1:2018-03-17 13:48:25
pool-1-thread-1给我一个线程:2018-03-17 13:48:25
。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

java 创建线程池的4中方式

标签:java 创建线程池的4中方式

原文地址:http://blog.51cto.com/13579086/2087880

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!