Java多线程____Executors线程池的使用和架构原理

来源:互联网 发布:适合学生的网络兼职 编辑:程序博客网 时间:2024/05/20 20:01

1.线程池API类型


1.创建一个可重用固定线程数的线程池

package com.frame.base.thread;import java.util.concurrent.Executors;import java.util.concurrent.ExecutorService;/** * Java线程:线程池 * @author Administrator  */public class TestExecutors {public static void main(String[] args) {// 创建一个可重用固定线程数的线程池,以共享的无界队列方式来运行这些线程,ExecutorService executorService = Executors.newFixedThreadPool(2);Thread t1 = new TestThread();Thread t2 = new TestThread();Thread t3 = new TestThread();// 将线程放入池中进行执行executorService.execute(t1);executorService.execute(t2);executorService.execute(t3);// 关闭线程池executorService.shutdown();}}class TestThread extends Thread {@Overridepublic void run() {System.out.println(Thread.currentThread().getName() + "运行中。。。");}}
1-1.运行结果

2.

//==========创建自定义线程池

int corePoolSize,//核心线程数--线程池初始化创建的线程数量  
int maximumPoolSize,//最大线程数,线程池中能创建的最大线程数  
long keepAliveTime,//线程存活时间  
TimeUnit unit,//线程存货时间单位  
BlockingQueue<Runnable> workQueue,//一个阻塞队列  

package com.frame.base.thread;import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.BlockingQueue;import java.util.concurrent.ThreadPoolExecutor;import java.util.concurrent.TimeUnit;/** * 自定义线程池 */public class MyExecutors {public static void main(String[] args) {/** * 定义一个阻塞队列 */BlockingQueue<Runnable> blockingQueue = new ArrayBlockingQueue<Runnable>(10);/** * 定义一个线程池执行器 */ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 3, 60,TimeUnit.SECONDS, blockingQueue);/** * 创建线程执行 */Thread t1 = new MyThread();Thread t2 = new MyThread();Thread t3 = new MyThread();// 将线程放入池中进行执行threadPoolExecutor.execute(t1);threadPoolExecutor.execute(t2);threadPoolExecutor.execute(t3);// 关闭线程池threadPoolExecutor.shutdown();}}class MyThread extends Thread {@Overridepublic void run() {System.out.println(Thread.currentThread().getName() + "运行中。。。");try {Thread.sleep(300L);} catch (InterruptedException e) {e.printStackTrace();}}}

//运行 结果

//==============线程池架构

阅读全文
0 0
原创粉丝点击