Java线程池

一、阻塞队列
在这里插入图片描述

二、队列

ConcurrentLinkedQueue(无边界队列)

import java.util.concurrent.ConcurrentLinkedQueue;

public class Test01 {
	
	public static void main(String[] args) {
		//无边界队列,没有长度限制
		ConcurrentLinkedQueue<String> clq = new ConcurrentLinkedQueue<>();
		//入队
		clq.add("java");
		clq.add("html");
		clq.add("css");
		//出队,并删除元素
		
		System.out.println(clq.poll());
		System.out.println("------------------");
		//打印元素,不删除元素
		clq.peek();
		System.out.println(clq.size());
	}
}



**BlockingQueue(阻塞队列)**
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

public class Test02 {
	/**
	 * @param args
	 * @throws InterruptedException 
	 */
	public static void main(String[] args) throws InterruptedException {
		//Blockingqueue阻塞队列
		BlockingQueue<String> bq = new LinkedBlockingQueue<>(3);
		bq.offer("java");
		bq.offer("cass");
		bq.offer("html");
		
		System.out.println(bq.poll());
		bq.offer("oracle",3,TimeUnit.SECONDS);

		System.out.println(bq.size());
	}
}


三、线程池ThreadPoolExecutor底层原理
在这里插入图片描述

案例:

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Test03 {
	public static void main(String[] args) {
		//1.新建线程池
		ThreadPoolExecutor pool = new ThreadPoolExecutor(1,2, 3, TimeUnit.SECONDS, new LinkedBlockingQueue(3));
		//2.执行第一个任务,由核心线程执行
		pool.execute(new sayThread());
		//3.执行第二个任务,放入队列中,还是由核心线程数执行,如果有新建线程,将分摊执行
		pool.execute(new sayThread());
		pool.execute(new sayThread());
		pool.execute(new sayThread());
		
		//4.执行第三个任务,将会新建线程执行。
		pool.execute(new sayThread());
		
		//5.执行第4个任务,会报错,因为最大线程数为2,核心线程数+新建线程已经为2
		pool.execute(new sayThread());
		
		//关闭线程池
		pool.shutdown();
	}
}

class sayThread implements Runnable{

	@Override
	public void run() {
		System.out.println(Thread.currentThread().getName());
	}

}

注意:线程池创建要使用ThreadPoolExecutor创建,避免OOM的产生。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值