package com.bupt.ThreadPoolDemo;
/**
* 創建線程方式四:線程池
* 好處:
* 1、提高響應速度,減少了創建新線程的時間
* 2、降低資源消耗,重複利用線程池中的線程,不需要每次都創建。
* 3、便於線程管理
* corePoolSize:核心池的大小
* maximumPool: 最大線程數
* keepAliveTime: 線程沒有任務時最多保持多長時間會中終止
*創建多線程:四種方式
*
*/
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
class Number implements Runnable{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
if( i % 2 == 0){
System.out.println(Thread.currentThread().getName()+": "+i);
}
}
}
}
class Number1 implements Runnable{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
if( i % 2 != 0){
System.out.println(Thread.currentThread().getName()+": "+i);
}
}
}
}
public class ThreadPool {
public static void main(String[] args) {
//1. 提供指定數量的線程池
ExecutorService service = Executors.newFixedThreadPool(10);
ThreadPoolExecutor service1 = (ThreadPoolExecutor) service;
//設置線程池的屬性
service1.setCorePoolSize(15);
//2. 執行指定的線程操作,需要提供實現Runnable接口測試或callable接口實現類的對象
service1.execute(new Number());//適合於Runnable
service1.execute(new Number1());//適合於Runnable
//service.submit;//適合使用Callable
//3.關閉連接池
service.shutdown();
}
}
多線程基礎五: 線程池創建多線程
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.