zoukankan      html  css  js  c++  java
  • 实现Callable接口创建线程

    创建执行线程有四种方式:

    • 实现implements接口创建线程
    • 继承Thread类创建线程
    • 实现Callable接口,通过FutureTask包装器来创建线程
    • 使用线程池创建线程

    下面介绍通过实现Callable接口来创建线程。

     1 package com.ccfdod.juc;
     2 
     3 import java.util.concurrent.Callable;
     4 import java.util.concurrent.ExecutionException;
     5 import java.util.concurrent.FutureTask;
     6 
     7 /**
     8  * 一、创建执行线程的方式三:实现Callable接口。相较于实现Runnable接口的方式,方法可以有返回值,并且可以抛出异常
     9  * 二、执行Callable方式,需要FutureTask实现类的支持,用于接收运算结果
    10  */
    11 public class TestCallable {
    12     public static void main(String[] args) {
    13         ThreadDemo td = new ThreadDemo();
    14 
    15         // 1.执行Callable方式,需要FutureTask实现类的支持,用于接收运算结果
    16         FutureTask<Integer> result = new FutureTask<>(td);
    17         new Thread(result).start();
    18 
    19         // 2.接收线程运算后的结果
    20         Integer sum;
    21         try {
    22             //等所有线程执行完,获取值,因此FutureTask 可用于 闭锁
    23             sum = result.get();
    24             System.out.println("-----------------------------");
    25             System.out.println(sum);
    26         } catch (InterruptedException | ExecutionException e) {
    27             e.printStackTrace();
    28         }
    29     }
    30 }
    31 
    32 class ThreadDemo implements Callable<Integer> {
    33 
    34     @Override
    35     public Integer call() throws Exception {
    36         int sum = 0;
    37         for (int i = 0; i <= 100000; i++) {
    38             System.out.println(i);
    39             sum += i;
    40         }
    41         return sum;
    42     }
    43 }
  • 相关阅读:
    树莓派4B(4G版本)安装Ubuntu 19.10
    PyQt5通过使用QSS语法制作精美界面
    PyQt5 界面设计和业务处理分离
    Python多线程同步
    PyQt界面
    pip设置
    Vim 常用配置
    python日期处理
    vue项目创建与使用
    vue 指令,成员,组件
  • 原文地址:https://www.cnblogs.com/ccfdod/p/6396012.html
Copyright © 2011-2022 走看看