java 线程池

一、语法

1、定义线程池

// n为线程池,线程数量
ExecutorService service = Executors.newFixedThreadPool(n);

2、提交线程对象到线程池

Future<类型> future = service.submit(线程对象);

获取返回值,Callable实现线程

System.out.println(future.get());

3、关闭线程

service.shutdown();

二、案例

1、线程类

package com.wt.pool;

import java.util.concurrent.Callable;

public class MyReturnStr implements Callable<String> {
    @Override
    public String call() throws Exception {
        return "Hello, World!!!";
    }
}

 

package com.wt.pool;

import java.util.concurrent.Callable;

public class MyReturnSum implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        int sum = 0;
        for (int i = 0; i < 101; i++) {
            sum+=i;
        }

        return sum;
    }
}

2、主类

package com.wt.pool;

import java.util.concurrent.*;

public class PoolMain {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 创建线程池
        ExecutorService service = Executors.newFixedThreadPool(2);
        // 提交/添加线程
        Future<String> future = service.submit(new MyReturnStr());
        // 获取返回值
        System.out.println(future.get());
        // 提交.添加线程
        Future<Integer> future1 = service.submit(new MyReturnSum());
        System.out.println(future1.get().intValue());;
        // 关闭线程
        service.shutdown();
    }
}

 

posted @ 2025-04-17 19:35  市丸银  阅读(19)  评论(0)    收藏  举报