Java.SE01.多线程_案例02

 1.线程池主要作用: ①控制线程数量 ②重用线程

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

/**
 * 线程池主要作用:
 * 	1:控制线程数量
 * 	2:重用线程
 * @author 爱吃木鱼的猫
 */
public class Demo01 {

	public static void main(String[] args) {
		ExecutorService threadPool=Executors.newFixedThreadPool(2);//容量为2的线程池
		for(int i=0;i<4;i++){
			Runnable runn = new Runnable(){
				public void run(){
					try{
					Thread t= Thread.currentThread();
					System.out.println("任务"+t.getName()+":开始...");
					Thread.sleep(3000);
					System.out.println("任务"+t.getName()+":结束");
					}catch(Exception e){
						System.out.println("线程被中断了!");
					}
				}
			};
			threadPool.execute(runn);
			//System.out.println("指派了一个任务"+i);
		}

		threadPool.shutdown();//停止
		//threadPool.shutdownNow();//立即停止
		System.out.println("停止了线程池");

	}

}

从结果可以看出:4个线程中2个可以先进入线程池中,剩下2个阻塞等待中,只要常量池中一旦有一个完成的剩下的便运行一个;

shutdown后,如果还有未完成的就继续完成(左图结果);

shutdownNow后,即使没有完成也要强制停止(右图结果)






猜你喜欢

转载自blog.csdn.net/u012761191/article/details/70039449