博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
创建多线程的 5 种方式
阅读量:4104 次
发布时间:2019-05-25

本文共 3993 字,大约阅读时间需要 13 分钟。

一、简介

使用多线程可以提高程序执行的效率,比如我们常见的多线程下载,批量发送文件等功能,常见的实现多线程的方法如下。多线程知识总结见:。

二、实现多线程的 5 种方法

1、实现 Runnable 接口
public class MyRunnable implements Runnable {   private static AtomicInteger count = new AtomicInteger(0);    @Override    public  void run() {        for (int i = 0; i < 20; i++) {            System.out.println(Thread.currentThread().getName() + ": " + count.incrementAndGet());        }    }    public static void main(String[] args) {        MyRunnable runnable = new MyRunnable();        Thread t1 = new Thread(runnable);        Thread t2 = new Thread(runnable);        Thread t3 = new Thread(runnable);        t1.start();        t2.start();        t3.start();    }}
2、继承Thread 类
public class MyThread extends Thread {    private static AtomicInteger count = new AtomicInteger(0);    @Override    public void run() {        for (int i = 0; i < 20; i++) {            System.out.println(Thread.currentThread().getName() + ": " + count.incrementAndGet());        }    }    public static void main(String[] args) {        MyThread t1 = new MyThread();        MyThread t2 = new MyThread();        MyThread t3 = new MyThread();        t1.start();        t2.start();        t3.start();    }}
3、匿名内部类的方式
public class MyInnerThread {    private static AtomicInteger count = new AtomicInteger(0);    public static void main(String[] args){        Thread t1=new Thread(new Runnable() {            @Override            public void run() {                for(int i=0;i<20;i++){                    System.out.println(Thread.currentThread().getName() + ": " + count.incrementAndGet());                }            }        });        t1.start();       new Thread(new Runnable() {            @Override            public void run() {                for(int i=0;i<20;i++){                    System.out.println(Thread.currentThread().getName() + ": " + count.incrementAndGet());                }            }        }).start();       //lambda 表达式        new Thread(() -> {            for(int i=0;i<20;i++){                System.out.println(Thread.currentThread().getName() + ": " + count.incrementAndGet());            }        }).start();    }}
4、使用 Callable 方式

我们使用 Thread 或者 Runnable 实现的多线程,在线程执行完毕后,不能返回结果。我们可以使用 Callable + Future 的方式实现多线程,Callable 执行任务,Future 获取结果

public class MyCallable {    public static void main(String[] args) {        CallableTest callable = new CallableTest();        //1.执行Callable方式,需要FutureTask实现类的支持,用于接收运算结果        FutureTask
result = new FutureTask
(callable); new Thread(result).start(); //2.接收线程运算后的结果 try { Integer sum = result.get(); System.out.println(sum); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } }}class CallableTest implements Callable
{ @Override public Integer call() throws Exception { int sum = 0; for (int i = 0; i < 20; i++) { sum++; } return sum; }}

FutureTask 提供了以下方法:

V get() : 异步获取结果,如果没有结果,该方法阻塞直到计算完成

V get(Long timeout , TimeUnit unit):异步获取结果,但有时间限制,超出限制,抛出异常
boolean isDone(): 任务十分执行完成,正常结果,抛出异常,中途取消都返回 true
boolean isCanceller():如果任务提前取消,返回 true
boolean cancel(boolean mayInterruptRunning): 使用 cancel(true) 尝试以中断线程的方式取消任务,取消成功,返回 true,如果任务还没开始或者已经完成调用的话但会返回 false,boolean mayInterruptRunning 表示十分以中断线程的方式取消任务。

其作用总结为:

1、动态获取结果
2、判断任务十分执行完成
3、取消任务
4、任务十分取消

5、线程池

创建一个固定大小的线程池,线程池的创建分为多种,具体我们下一篇分析。

public class MyThreadPool {    private static AtomicInteger count = new AtomicInteger(0);    public static void main(String[] args){        //创建固定大小的线程池      ExecutorService executorService = Executors.newFixedThreadPool(3);              for (int i = 0; i <3 ; i++) {            executorService.submit(()->{                for (int j = 0; j < 20; j++) {                    System.out.println(Thread.currentThread().getName() + ": " + count.incrementAndGet());                }            });        }    }}

—— 完

ABOUT ME

我的 Github:

CSDN:
个人网站:

推荐阅读

转载地址:http://iffsi.baihongyu.com/

你可能感兴趣的文章
触目惊心:比特币到底消耗了多少能源?
查看>>
如何判断一家互联网公司要倒闭了?
查看>>
想快速上手机器学习?来看下这个 GitHub 项目!
查看>>
GitHub 标星 3.6k,一本开源的深度学习中文教程!
查看>>
9 款你不能错过的 JSON 工具
查看>>
就在昨天,全球 42 亿 IPv4 地址宣告耗尽!
查看>>
200页!分享珍藏很久的Python学习知识手册(附链接)
查看>>
4 岁小女孩给 Linux 内核贡献提交
查看>>
推荐几个私藏很久的技术公众号给大家
查看>>
王垠受邀面试阿里 P9,被 P10 面跪后网上怒发文,惨打 325 的 P10 赵海平回应了!...
查看>>
Python 趣味打怪:147 段简单代码助你从入门到大师
查看>>
卧槽!小姐姐用动画图解 Git 命令,这也太秀了吧?!
查看>>
厉害了!Python 编辑器界的神器 Jupyter ,推出官方可视化 Debug 工具!
查看>>
卧槽!Java 虚拟机竟然还有这些性能调优技巧...
查看>>
听说玩这些游戏能提升编程能力?
查看>>
7 年工作经验,面试官竟然还让我写算法题???
查看>>
被 Zoom 逼疯的歪果仁,造出了视频会议机器人,同事已笑疯丨开源
查看>>
再见,Eclipse...
查看>>
如果你还不了解 RTC,那我强烈建议你看看这个!
查看>>
沙雕程序员在无聊的时候,都搞出了哪些好玩的小玩意...
查看>>