Java线程池

本文介绍如何使用Java的线程池来管理并发任务,包括创建固定大小的线程池和缓存线程池,并通过示例展示了不同类型的线程池如何影响任务执行顺序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如果仅需要为一个任务创建一个线程,就使用Thread类。如果需要为多个任务创建线程,最好使用线程池。

线程池是管理并发执行任务个数的理想方法。Java提供Executor接口来执行线程池中的任务,提供ExcutorService接口来管理和控制任务。

java.util.concurrent.Executor接口的方法如下:

+executor(Runnable object):void  执行可运行任务

 

java.util.concurrent.ExecutorService接口的方法如下:

+shutdown():void   关闭执行器,但是允许执行器中的任务执行完。一旦关闭,则不再接收新任务

+shutdownNow():List<Runnable> 立刻关闭执行器,即使池中还有未完成的线程,返回一个未完成任务列表

+isShutdaown():boolean如果执行器已经关闭,返回true

+isTerminated():boolean如果池中所有任务终止,则返回true

 

java.util.concurrent.Executors类的方法如下:

+newFixedThreadPool(numberOfThreads:int):ExecutorService  创建一个可以并行运行指定数目的线程池。一个线程在当前任务已经完成的情况下可以重用,来执行另一个任务。

+newCachedThreasPool():ExecutorService   创建一个线程池,它会在必要的时候创建新的线程,但是如果之前创建的线程可用,则先重用之前创建的线程。

package test;

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

public class project1 {
	 
   public static void main(String []args) {

	     Runnable printA=new printChar('A',100);
	     Runnable printB=new printChar('B',100);
		 Runnable print100=new printNum(100);

         ExecutorService executor=Executors.newFixedThreadPool(3);
         executor.execute(printA);
         executor.execute(printB);
         executor.execute(print100);
         executor.shutdown();
	}
}

 class printChar implements Runnable{
	private char charToPrint;
	private int time;
	public printChar(char charToPrint,int time) {
		this.charToPrint=charToPrint;
		this.time=time;
	}
	@Override
	public  void run() {
			for(int i=0;i<time;i++) {
				System.out.print(charToPrint);
			 }
			
	}
}
 
 class printNum implements Runnable{
		
		private int lastNum;
		public printNum(int lastNum) {
			this.lastNum=lastNum;
		}
		@Override
		public void run() {
			for(int i=0;i<lastNum;i++) {			
				System.out.print(i+" ");
			}
	 }
 }

如果修改为 ExecutorService executor=Executors.newFixedThreadPool(1);这三个任务将顺序执行,输出完A再输出B,最后输出数字。

如果修改为  ExecutorService executor=Executors.newCachedThreadPool();将为每个等待的任务创建一个新线程,所以,所有的任务都并发的执行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值