多线程基础五: 线程池创建多线程

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();
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章