Java多线程实战

Java多线程实战

java多线程(超详细)
java自定义线程池总结
Java 8 中的 CompletableFuture 太好用了!20 个示例

Java创建线程方式

  • 方法1,继承Thread类

  • 方法2,实现Runable接口

  • 方法2-2,匿名内部类形式+lambda表达式

  • 方法3,实现Callable接口,允许有返回值

  • 方法4,线程池方式
    常见线程池:
    在这里插入图片描述

public class ThreadTest {
    public static void main(String[] args) {
        // 方法一
        MyThread myThread = new MyThread();
        myThread.start();
        // 方法2
        MyRunable myRunable = new MyRunable();
        Thread thread = new Thread(myRunable);
        thread.start();
        // 方法2-2
        Thread thread1 = new Thread(() -> {
            try {
                Thread.sleep(5);
                System.out.println(Thread.currentThread().getName() + "匿名线程形式运行中");
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        thread1.start();

        // 方法3
        MyCallable myCallable = new MyCallable();
        FutureTask futureTask = new FutureTask<>(myCallable);
        Thread thread2 = new Thread(futureTask);
        thread2.start();
        try {
            Object o = futureTask.get();
            System.out.println(o);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }

        // 方法4-线程池,常有线程池
        ExecutorService threadPool = Executors.newFixedThreadPool(10);
        threadPool.execute(myThread);
        threadPool.execute(myRunable);
        Future<?> ret = threadPool.submit(() -> {
            try {
                Thread.sleep(5);
                System.out.println(Thread.currentThread().getName() + "Callable形式运行中");
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return "yangshun";
        });
        try {
            System.out.println(ret.get());
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
        threadPool.shutdown();

        // 方法4-2:自定义线程池
        ThreadPoolExecutor pool = new ThreadPoolExecutor(
                1, 				//coreSize
                2, 				//MaxSize
                60, 			//60
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<Runnable>(3),			//指定一种队列 (有界队列),
                new ThreadPoolExecutor.CallerRunsPolicy()                          //自定义拒绝策略
                //, new DiscardOldestPolicy()               //可以使用默认拒绝策略
        );
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                // 核心线程数
                3,
                // 最大线程数
                5,
                // 空闲线程最大存活时间
                60L,
                // 空闲线程最大存活时间单位
                TimeUnit.SECONDS,
                // 等待队列及大小
                new ArrayBlockingQueue<>(100),
                // 创建新线程时使用的工厂
                Executors.defaultThreadFactory(),
                // 当线程池达到最大时的处理策略
//                new ThreadPoolExecutor.AbortPolicy()          // 抛出RejectedExecutionHandler异常
                new ThreadPoolExecutor.CallerRunsPolicy()       // 交由调用者的线程执行
//                new ThreadPoolExecutor.DiscardOldestPolicy()  // 丢掉最早未处理的任务
//                new ThreadPoolExecutor.DiscardPolicy()        // 丢掉新提交的任务
        );
        // 总共5个任务
        for (int i = 1; i <= 5; i++) {
            int taskIndex = i;
            executor.execute(() -> {
                System.out.println("线程 " + Thread.currentThread().getName() + " 正在执行任务 " + taskIndex);
                // 每个任务耗时1秒
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
        executor.shutdown();
        System.out.println("主线程运行结束");
    }
    @Test
    public void test() {
        ExecutorService threadPool = Executors.newCachedThreadPool();
        for(int i = 0; i < 100; i++) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + "正在执行中。。。");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
        }

        threadPool.shutdown();
    }

}
class MyCallable implements Callable{

    @Override
    public Object call() throws Exception {
        try {
            Thread.sleep(5);
            System.out.println(Thread.currentThread().getName() + "Callable形式运行中");
            Thread.sleep(100);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return "运行成功!yes";
    }
}
class MyThread extends Thread {

    @Override
    public void run() {
        try {
            Thread.sleep(5);
            System.out.println(Thread.currentThread().getName() + "运行中");
            Thread.sleep(100);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

class MyRunable implements Runnable {

    @Override
    public void run() {
        try {
            Thread.sleep(5);
            System.out.println(Thread.currentThread().getName() + "Runable形式运行中");
            Thread.sleep(100);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

SpringBoot创建线程方式

【并发编程】SpringBoot创建线程池的六种方式

java并发学习–第二章 spring boot实现线程的创建

CompletableFuture使用

CompletableFuture 使用详解
CompletableFuture使用详解(全网看这一篇就行)

带你了解了解Future和CompletableFuture

CompletableFuture使用详解

public class CompletableFutureTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<String> stringCompletableFuture = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(100);
                System.out.println(Thread.currentThread().getName() + "线程运行中。。。");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return "yangshun";
        });
        ExecutorService threadPool = Executors.newFixedThreadPool(10);
        CompletableFuture<String> stringCompletableFuture1 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(100);
                System.out.println(Thread.currentThread().getName() + "指定线程池线程运行中。。。");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return "yangshun1";
        }, threadPool);
        System.out.println(stringCompletableFuture.get());
        System.out.println(stringCompletableFuture1.get());
        CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> {
            try {
                Thread.sleep(100);
                System.out.println(Thread.currentThread().getName() + "runAsync线程运行中");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        System.out.println(voidCompletableFuture.get());
        stringCompletableFuture.thenAcceptAsync(str -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread().getName() + "thenAcceptAsync线程运行中,返回值为:" + str);
        });

        System.out.println("主线程运行结束");
        
    }
}

参考:
Java多线程(十): FutureTask CompletableFuture详解

CompletableFuture用法详解

CompletableFuture使用教程

CompletableFuture实战
CompletableFuture使用教程

CompletableFuture在异常处理方面的一些常见问题和解决方案

CompletableFuture异常优雅处理方式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值