创建线程的三种方法,线程池的创建方式

创建线程的三种方法

1、继承Thread类

2、实现Runable接口,没有返回值,不抛异常

3、实现Callable接口,有返回值,会抛异常

public class CallableDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask<Integer> futureTask = new FutureTask<>(new MyThread());
        new Thread(futureTask, "AA").start();
        int result01 = 100;

//        while (!futureTask.isDone()){
//
//        }

        int result02 = futureTask.get();//会导致阻塞
        System.out.println("result=" + (result01 + result02));
    }
}

class MyThread implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        System.out.println("callable come in ...");
        return 1024;
    }
}

Executors.newCachedThreadPool

img

private static void cachedThreadPool() {
    //不定量线程
    ExecutorService threadPool = Executors.newCachedThreadPool();
    try {
        for (int i = 0; i < 9; i++) {
            threadPool.execute(() -> {
                System.out.println(Thread.currentThread().getName()+"\t办理业务");
            });
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        threadPool.shutdown();
    }
}

Executors.newSingleThreadExecutor

img

private static void singleThreadPool() {
    //一池1个线程
    ExecutorService threadPool = Executors.newSingleThreadExecutor();
    try {
        for (int i = 0; i < 9; i++) {
            threadPool.execute(() -> {
                System.out.println(Thread.currentThread().getName() + "\t办理业务");
            });
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        threadPool.shutdown();
    }
}

Executors.newFixedThreadPool

img

//一池5个线程
ExecutorService threadPool = Executors.newFixedThreadPool(5);
//一般常用try-catch-finally
//模拟10个用户来办理业务,每个用户就是一个线程
try {
    for (int i = 0; i < 9; i++) {
        threadPool.execute(() -> {
            System.out.println(Thread.currentThread().getName() + "\t办理业务");
        });
    }

} catch (Exception e) {
    e.printStackTrace();
} finally {
    threadPool.shutdown();
}

All

package com.tyred.demo.thread;

import java.time.LocalDate;
import java.util.concurrent.*;

/**
 * 第四种使用Java多线程的方式,线程池
 */
public class MyThreadPoolDemo {
    public static void main(String[] args) {
        System.out.println("Fixed Thread Pool");
        fixedThreadPool();
//        System.out.println("Single Thread Pool");
//        singleThreadPool();
//        System.out.println("Cached Thread Pool");
//        cachedThreadPool();
//        System.out.println("Custom Thread Pool");
//        customThreadPool();

        // 获取今年的天数
//        int daysOfThisYear = LocalDate.now().lengthOfYear();
//        System.out.println(daysOfThisYear);
 获取指定某年的天数
//        System.out.println(LocalDate.of(2012, 1, 1).lengthOfYear());
//        System.out.println(LocalDate.MAX);
    }

    private static void customThreadPool() {
        ExecutorService threadPool =
                new ThreadPoolExecutor(2,
                        5,
                        1L,
                        TimeUnit.SECONDS,
                        new LinkedBlockingQueue<>(3),
                        Executors.defaultThreadFactory(),
                        new ThreadPoolExecutor.AbortPolicy()
                );
        try {
            for (int i = 0; i < 9; i++) {
                threadPool.execute(() -> {
                    System.out.println(Thread.currentThread().getName() + "\t办理业务");
                });
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            threadPool.shutdown();
        }
    }

    private static void cachedThreadPool() {
        //不定量线程
        ExecutorService threadPool = Executors.newCachedThreadPool();
        try {
            for (int i = 0; i < 9; i++) {
                threadPool.execute(() -> {
                    System.out.println(Thread.currentThread().getName() + "\t办理业务");
                });
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            threadPool.shutdown();
        }
    }

    private static void singleThreadPool() {
        //一池1个线程
        ExecutorService threadPool = Executors.newSingleThreadExecutor();
        try {
            for (int i = 0; i < 9; i++) {
                threadPool.execute(() -> {
                    System.out.println(Thread.currentThread().getName() + "\t办理业务");
                });
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            threadPool.shutdown();
        }
    }

    private static void fixedThreadPool() {
        //一池5个线程
        ExecutorService threadPool = Executors.newFixedThreadPool(5);
        //一般常用try-catch-finally
        //模拟10个用户来办理业务,每个用户就是一个线程
        try {
            for (int i = 0; i < 9; i++) {
                threadPool.execute(() -> {
                    System.out.println(Thread.currentThread().getName() + "\t办理业务");
                });
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
//            threadPool.shutdown();
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

TyRed08

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值