线程池

所谓线程池就是多个线程封装在一起操作,线程池对任务进行操作的时候,有几种运行操作型式,单线程,无限多,限定长度,对线程池操作的核心就类和方法定义在java.util.concurrent包中,其中有两个比较核心 的接口:

1.普通的执行线程池定义:Interface ExecutorService

2.调度线程池:java.util.concurrent.ScheduledExecutorService

创建一个线程池可以使用java.util.concurrent.Executors类

。创建无大小的线程池:public static ExecutorService newCachedThreadPool()

。创建固定大小的线程池:public static ExecutorService newFixedThreadPool(int nThreads)

。单线程池:public static ScheduledExecutorService newSingleThreadScheduledExecutor()

。穿件定时调度池:public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)


几种的实现demo

package com.wjx.sayHello;

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

public class TestDemo {
	
	public static void main(String[] args) throws InterruptedException{
		/*
		 * ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
		for(int x=0;x<10;x++){
			//Thread.sleep(200);
			int temp=x;
			newCachedThreadPool.submit(()->{
				System.out.println(Thread.currentThread().getName()+"==="+temp);
			});
		}
		
		newCachedThreadPool.shutdown();*/
//		ExecutorService newCachedThreadPool = Executors.newSingleThreadExecutor();
//		for(int x=0;x<10;x++){
//			//Thread.sleep(200);
//			int temp=x;
//			newCachedThreadPool.submit(()->{
//				System.out.println(Thread.currentThread().getName()+"==="+temp);
//			});
//		}
//		
//		newCachedThreadPool.shutdown();
//		ExecutorService newCachedThreadPool = Executors.newFixedThreadPool(4);
//		for(int x=0;x<10;x++){
//			//Thread.sleep(200);
//			int temp=x;
//			newCachedThreadPool.submit(()->{
//				System.out.println(Thread.currentThread().getName()+"==="+temp);
//			});
//		}
//		
//		newCachedThreadPool.shutdown();
		ScheduledExecutorService newCachedThreadPool = Executors.newScheduledThreadPool(1);
		for(int x=0;x<10;x++){
			//Thread.sleep(200);
			int temp=x;
			newCachedThreadPool.scheduleAtFixedRate(new Runnable(){

				@Override
				public void run() {
					System.out.println(Thread.currentThread().getName()+"==="+temp);
					System.out.println("****************************************");
					
				}
				
			}, 3, 2, TimeUnit.SECONDS);
		}
		
		
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值