Java并发——实现多线程的方式

文章介绍了在Java中实现多线程的三种主要方法:1)继承Thread类并重写run方法;2)实现Runnable接口,通过newThread(runnable).start()启动;3)实现Callable接口,结合FutureTask和ExecutorService进行异步计算并获取结果。文中还展示了每种方法的代码示例,包括Future的阻塞特性以及线程池的使用。
摘要由CSDN通过智能技术生成

Java实现多线程的方式

在这里插入图片描述

继承Thread类

重写run方法,使用时,调用start方法

实现Runnable接口

适用于已经继承过类的情况,实现run方法,使用时,

new Thread(runnable的实例).start()

实现Callable接口

实现Callable接口,通过FutureTask包装器来创建Thread线程。

  1. 创建实现Callable接口的实例
  2. 封装任务为FutureTask
  3. Thread开启线程
		//创建线程任务
        Callable<Integer> callable = ()->{
            System.out.println("线程任务开始执行了");
            Thread.sleep(2000);
            return 1;
        };
        //将任务封装为FutureTask
        FutureTask<Integer> task = new FutureTask<>(callable);
        //开启线程
        new Thread(task).start();

        System.out.println("线程启动之后,结果返回之前");

        //拿到结果
        Integer res = task.get();
        System.out.println("主线程中异步任务执行的结果为:"+res);
    }

结果
在这里插入图片描述

使用ExecutorService、Callable、Future

注意,Future的get方法是阻塞的,即线程无返回结果,get方法会一直等待。

package com.Concurrent;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class myThread4 {
    public static void main(String[] args) throws Exception{
        System.out.println("主程序开始运行");
        Date startTime = new Date();
        int taskSize = 5;
        //创建一个线程池
        ExecutorService executorService = Executors.newFixedThreadPool(taskSize);
        //创建多个有返回值的任务
        List<Future> futureList = new ArrayList<Future>();
        for(int i=0;i<taskSize;i++){
            Callable callable = new MyCallable(i);
            //执行任务获取Future对象
            Future future = executorService.submit(callable);
            futureList.add(future);
        }
        //关闭线程池
        executorService.shutdown();
        //获取所有并发任务的运行结果
        for(Future future:futureList){
            System.out.println(">>> "+future.get().toString());
        }
        Date endTime = new Date();
        System.out.println("主程序结束运行,程序运行耗时 "+(endTime.getTime()-startTime.getTime())+" 毫秒");
    }
}

class MyCallable implements Callable<Object>{
    private int taskNum;
    MyCallable(int taskNum){
        this.taskNum = taskNum;
    }
    public Object call()throws Exception{
        System.out.println(">>> "+taskNum + " 线程任务启动");
        Date startTime = new Date();
        Thread.sleep(1000);
        Date endTime = new Date();
        long time = endTime.getTime()-startTime.getTime();
        System.out.println("--- "+taskNum+" 线程任务终止");
        return taskNum + "线程任务返回运行结果,当前任务耗时 "+time+" 毫秒";
    }
}

结果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值