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

java线程-四种线程池的使用

时间:2020-07-01 22:20:39      阅读:84      评论:0      收藏:0      [点我收藏+]

标签:rate   弊端   news   class   run   sys   fixed   cond   使用   

一、为什么要使用线程池

先谈谈直接建立Thread的弊端:

1、每次执行不同的任务都需要新建线程,浪费资源和时间

2、缺乏统一的管理,容易出现自锁的现象

再来对比说说使用线程池的优势:

1、起到重用线程的作用,减少时间和资源的浪费

2、可有效的控制线程的总数,避免资源的浪费

3、有更多的功能比如定期执行

二、直接上代码:

单线程化线程池:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
 * 
 * @version: 1.1.0
 * @Description: 单线程化线程池
 * @author: wsq
 * @date: 2020年7月1日下午9:02:00
 */
public class SingleThreadPoolTest {
public static void main(String[] args) {
    ExecutorService singleThreadPool = Executors.newSingleThreadExecutor();
    for(int i = 0;i < 100;i++) {
        int j = i;
        singleThreadPool.execute(() -> {
            System.out.println(Thread.currentThread().getName()+":"+j);
        });
    }
}
}

定长线程池:

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

/**
 * 
 * @version: 1.1.0
 * @Description: 定长线程池,规定允许呦最大数量的线程
 * @author: wsq
 * @date: 2020年7月1日下午8:20:41
 */
public class FixThreadPoolTest {
public static void main(String[] args) {
    // 传入最大线程的数量
    ExecutorService fixThreadPool = Executors.newFixedThreadPool(6);
    for(int i = 0;i < 100;i++) {
        int j = i;
        fixThreadPool.execute(() -> System.out.println(Thread.currentThread().getName()+":"+j));
    }
    
}
}

缓存线程池:

/**
 * 
 * @version: 1.1.0
 * @Description: 缓存线程池,此线程池不会对线程池大小做限制,jvm根据任务情况自动增减线程
 * 
 * @author: wsq
 * @date: 2020年7月1日下午8:09:39
 */
public class CacheThreadPoolTest {
public static void main(String[] args) {
    ExecutorService cacheThreadPool = Executors.newCachedThreadPool();
    for(int i = 0;i < 100;i++) {
        int j = i;
        cacheThreadPool.execute(() -> {
            System.out.println(Thread.currentThread().getName()+":"+j);
        });
    }
}
}

周期线程池:

/**
 * 
 * @version: 1.1.0
 * @Description: 周期线程池
 * @author: wsq
 * @date: 2020年7月1日下午8:32:13
 */
public class ScheduleThreadPool {
    public static void main(String[] args) {
        ScheduledExecutorService scheduleThreadPool = Executors.newScheduledThreadPool(3);
        Runnable r1 = () -> {System.out.println("线程:"+Thread.currentThread().getName()+"3秒后开始执行任务r1");};
        scheduleThreadPool.schedule(r1, 3, TimeUnit.SECONDS);
        Runnable r2 = () -> {System.out.println("线程:"+Thread.currentThread().getName()+"延迟2秒每3秒执行任务r2");};
        scheduleThreadPool.scheduleAtFixedRate(r2, 2, 3, TimeUnit.SECONDS);
        Runnable r3 = () -> {System.out.println("线程开始执行r3了");};
        for(int i = 0;i < 50;i++) {
            scheduleThreadPool.execute(r3);
        }
    }
}

 

java线程-四种线程池的使用

标签:rate   弊端   news   class   run   sys   fixed   cond   使用   

原文地址:https://www.cnblogs.com/mcjhcnblogs/p/13221594.html

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