线程池、Callable和 Runnable 区别

线程池创建的方法

  1. Single Thread Executor:只有一个线程的线程池,因此所有提交的任务顺序执行代码, Executors.newSingleThreadExecutor
  2. Cached Thread Pool:线程池里有很多线程需要同时执行,老得线程将被新的任务出发重新执行,如果线程超过60秒内没有执行,那么将被终止并从池中删除Executors.newCachedThreadPool
  3. Fixed Thread Pool:拥有固定线程数的线程池,如果没有任务执行,那么线程会一直等待Executors.newFixedThreadPool(4). 初始化4个线程的线程池,可以随便设置,也可以和cpu核数相同Runtime.getRuntime().availableProcessors()
  4. Scheduled Thread Pool:用来调度即将执行的任务的线程池 Executors.newScheduledThreadPool
  5. Single Thread Scheduled Pool:只有一个线程,用来调度任务在指定时间执行Executors.newSingleThreadScheduledExecutor

Callable 和 Runnable 区别

1.Callable 使用 call() 方法, Runnable 使用 run() 方法
2.call() 可以返回值, 而 run()方法不能返回。
3.call() 可以抛出受检查的异常,比如ClassNotFoundException, 而run()不能抛出受检查的异常。
例子 Runable

package org.shareing.myThreadool;

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

public class ThreadPoolWithRunable {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 5; i++) {
            //提交任务
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println("thread name:"+Thread.currentThread().getName());
                    try{
                        Thread.sleep(1000);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            });
        }
        executorService.shutdown();
    }
}

实验结果:

thread name:pool-1-thread-1
thread name:pool-1-thread-3
thread name:pool-1-thread-2
thread name:pool-1-thread-4
thread name:pool-1-thread-5

例子 callable

package org.shareing.myThreadool;

import java.util.concurrent.*;

public class ThreadPoolWithCallable {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
        for (int i = 0; i < 10; i++) {
            //提交任务
            Future<String> submit = executorService.submit(new Callable<String>() {
                @Override
                public String call() throws Exception {
                    return "b--"+Thread.currentThread().getName();
                }
            });
            //从future get方法是被阻塞的 要等到线程返回结果才能继续
            System.out.println(submit.get());
        }
        executorService.shutdown();
    }
}

实验结果:

b--pool-1-thread-1
b--pool-1-thread-2
b--pool-1-thread-3
b--pool-1-thread-4
b--pool-1-thread-1
b--pool-1-thread-2
b--pool-1-thread-3
b--pool-1-thread-4
b--pool-1-thread-1
b--pool-1-thread-2

例子Callable:

package org.shareing.myThreadool;

import java.util.concurrent.Callable;

public class TaskWithResult implements Callable<String> {
    private int id;

    public TaskWithResult(int id) {
        this.id = id;
    }
    @Override
    public String call() throws Exception {
        return "result of TaskWithResult " + id;
    }
}
package org.shareing.myThreadool;

import java.util.ArrayList;
import java.util.concurrent.*;

public class ThreadPoolWithCallable001 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService exec = Executors.newCachedThreadPool();
        ArrayList<Future<String>> results = new ArrayList<Future<String>>();    //Future 相当于是用来存放Executor执行的结果的一种容器
        for (int i = 0; i < 10; i++) {
            results.add(exec.submit(new TaskWithResult(i)));
        }
        for (Future<String> fs : results) {
            if (fs.isDone()) {
                System.out.println(fs.get());
            } else {
                System.out.println("Future result is not yet complete");
            }
        }
        exec.shutdown();
    }
}

实验结果:

result of TaskWithResult 0
result of TaskWithResult 1
result of TaskWithResult 2
result of TaskWithResult 3
result of TaskWithResult 4
result of TaskWithResult 5
result of TaskWithResult 6
result of TaskWithResult 7
Future result is not yet complete
result of TaskWithResult 9

例子Runnable:

package org.shareing.myThreadool;

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

public class LiftOff implements Runnable{
    protected int countDown = 10;
    private static int taskCount = 0;
    private final int id = taskCount++;

    public LiftOff() {

    }

    public LiftOff(int countDown) {
        this.countDown = countDown;
    }

    public String status() {
        return "#" + id + "(" + (countDown > 0 ? countDown : "LiftOff! ") + ")";
    }

    @Override
    public void run() {
        while (countDown-- > 0) {
            System.out.print(status());
            Thread.yield();
        }
        System.out.println();
    }

    public static void main(String[] args) {
        ExecutorService exec = Executors.newFixedThreadPool(1);
        for (int i = 0; i < 5; i++) {
            exec.execute(new LiftOff());
        }
        exec.shutdown();
    }
}

实验结果:

#0(9)#0(8)#0(7)#0(6)#0(5)#0(4)#0(3)#0(2)#0(1)#0(LiftOff! )
#1(9)#1(8)#1(7)#1(6)#1(5)#1(4)#1(3)#1(2)#1(1)#1(LiftOff! )
#2(9)#2(8)#2(7)#2(6)#2(5)#2(4)#2(3)#2(2)#2(1)#2(LiftOff! )
#3(9)#3(8)#3(7)#3(6)#3(5)#3(4)#3(3)#3(2)#3(1)#3(LiftOff! )
#4(9)#4(8)#4(7)#4(6)#4(5)#4(4)#4(3)#4(2)#4(1)#4(LiftOff! )
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值