首页 技术 正文
技术 2022年11月10日
0 收藏 404 点赞 4,442 浏览 1648 个字

实现线程的方式有四种:

1,实现runnable接口:

2,继承Thread。

3,也就是本节的Callable接口。

4,使用线程池。

区别:

实现Callable接口的方式,相较于实现Runnable接口方式,可以有返回值,并且可以抛出异常。

执行 Callable 方式,需要 FutureTask 实现类的支持,用于接收运算结果。  FutureTask 是  Future 接口的实现类

FutureTask 可用于闭锁,FutureTask.get()方法用于获取线程结果,在线程里面的call方法没有执行完,获取到结果之前,FutureTask.get()之后的代码不会执行

效果类似于countDownLatch,countDownLatch在所有运行结束之前,latch.await()之后代码不会执行。

步骤:

1,新建一个线程类实现Callable接口,Callable接口里面有泛型,用来定义返回结果类型,重写call方法

call方法的返回类型即使泛型的结果类型:

并且call方法能抛出异常:

class ThreadDemo implements Callable<Integer>{    @Override
public Integer call() throws Exception {

2,实例化线程类:

ThreadDemo td = new ThreadDemo();

3,使用FutureTask类,参数就是线程类对象。

        //1.执行 Callable 方式,需要 FutureTask 实现类的支持,用于接收运算结果。
FutureTask<Integer> result = new FutureTask<>(td);

4,把FutureTask对象作为Thread类参数,启动线程:

new Thread(result).start();

5,通过FutureTask对象,获取线程执行结果:

Integer sum = result.get();  //FutureTask 可用于 闭锁

实例:

package com.atguigu.juc;import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/*
* 一、创建执行线程的方式三:实现 Callable 接口。 相较于实现 Runnable 接口的方式,方法可以有返回值,并且可以抛出异常。
*
* 二、执行 Callable 方式,需要 FutureTask 实现类的支持,用于接收运算结果。 FutureTask 是 Future 接口的实现类
*/
public class TestCallable { public static void main(String[] args) {
ThreadDemo td = new ThreadDemo();
//1.执行 Callable 方式,需要 FutureTask 实现类的支持,用于接收运算结果。
FutureTask<Integer> result = new FutureTask<>(td);
new Thread(result).start(); //2.接收线程运算后的结果
try {
Integer sum = result.get(); //FutureTask 可用于 闭锁
System.out.println(sum);
System.out.println("------------------------------------");
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}class ThreadDemo implements Callable<Integer>{ @Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 0; i <= 1000; i++) {
sum += i;
}
return sum;
}}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,992
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,506
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,349
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,134
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,767
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,844