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

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 {
	@Override
	public 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 {
	@Override
	public void run() {
		System.out.println(Thread.currentThread().getName() + "运行中。。。");
		try {
			Thread.sleep(300L);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

//运行 结果

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

posted @ 2017-07-14 17:04  蜜獾互联网  阅读(3)  评论(0编辑  收藏  举报  来源