多线程_线程池

线程池:
    API: ExecutorService(线程池接口) Executors(线程池的工厂类 用于创建并返回不同类型的线程池)
    方法:
        void execute(Runnable command): 无返回值 一般用来执行Runnable接口的实现类的线程
        <T> Future<T> submit(Callable<T> task): 有返回值 一般用来执行Callable接口的实现类的线程

创建线程池

ExecutorService service = Executors.newFixedThreadPool(int nThreads);

关闭线程池

service.shutdown();

线程池实例一:线程类实现Runnable接口

public class TestPool {

    public static void main(String[] args) {
        //1.创建服务 创建线程池(参数为线程池大小)
        ExecutorService service = Executors.newFixedThreadPool(3);

        service.execute(new MyThread());
        service.execute(new MyThread());
        service.execute(new MyThread());
        service.execute(new MyThread());
        service.execute(new MyThread());

        //2.关闭连接
        service.shutdown();
    }
}

class MyThread implements Runnable{

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
}

运行效果

线程池实例二:线程类实现Callable接口

public class Test {
    public static void main(String[] args) {
        TestThread testThread01 = new TestThread("testThread01");
        TestThread testThread02 = new TestThread("testThread02");
        TestThread testThread03 = new TestThread("testThread03");
 
        //创建执行服务(线程池)
        ExecutorService service = Executors.newFixedThreadPool(10);
 
        //提交执行 并通过Future<Boolean>接收返回值
        Future<Boolean> result01 = service.submit(testThread01);
        Future<Boolean> result02 = service.submit(testThread02);
        Future<Boolean> result03 = service.submit(testThread03);
        //获取返回值
        try {
            boolean getReturn01 = result01.get();
            boolean getReturn02 = result02.get();
            boolean getReturn03 = result03.get();
 
            //输出返回值
            System.out.println(getReturn01);
            System.out.println(getReturn02);
            System.out.println(getReturn03);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        } finally {
            //关闭服务
            service.shutdown();
        }
    }
}
 
class TestThread implements Callable<Boolean> {
 
    String currentThreadName;
 
    public TestThread(String currentThreadName) {
        this.currentThreadName = currentThreadName;
    }
 
    @Override
    public Boolean call() throws Exception {
        System.out.println(currentThreadName);
        return true;
    }
}

运行效果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值