java.util.concurrent.RunnableFuture

本文深入探讨了Java并发编程中RunnableFuture接口的使用,包括其类型参数、超接口、已知子接口和实现类,以及接口中的方法概述。重点介绍了如何通过成功执行run方法来设置Future结果,除非被取消。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java.util.concurrent

Interface RunnableFuture<V>

    • Method Summary

      Methods  
      Modifier and Type Method and Description
      void run()
      Sets this Future to the result of its computation unless it has been cancelled.
    • Method Detail

      • run
        void run()
        Sets this Future to the result of its computation unless it has been cancelled.
        Specified by:
        run in interface  Runnable
        See Also:
        Thread.run()
package ajiayou.index0711.demo03; import java.util.Random; import java.util.concurrent.Callable; public class Match2 implements Callable<Integer> { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public Integer call() throws Exception { Random r = new Random(); //这里是随机数 int speed = r.nextInt(100); int dist = 0; for(int i = 1; i<=100; i++) { //睡眠100毫秒 Thread.sleep(30); //Thread.currentThread().getName() //获得当前线程的名称 dist += i * speed; System.out.println(this.getName() + "已前进" + (dist) + "米(" + speed + "米/秒)"); } return dist; } } /* 注释补充:创建一个线程 Java 提供了三种创建线程的方法: 1.通过继承 Thread 类本身; 2.通过实现 Runnable 接口; 3.通过 Callable 和 Future 创建线程。 创建 Callable 接口的实现类,并实现 call() 方法,该 call() 方法将作为线程执行体,并且有返回值。 创建 Callable 实现类的实例,使用 FutureTask 类来包装 Callable 对象,该 FutureTask 对象封装了该 Callable 对象的 call() 方法的返回值。 使用 FutureTask 对象作为 Thread 对象的 target 创建并启动新线程。 调用 FutureTask 对象的 get() 方法来获得子线程执行结束后的返回值。 */ package ajiayou.index0711.demo03; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class Test2 { public static void main(String[] args) throws ExecutionException, InterruptedException { ExecutorService es = Executors.newFixedThreadPool(3); //创建了3个线程 Match2 m = new Match2(); m.setName("java"); Match2 m1 = new Match2(); m1.setName("mysql"); Match2 m2 = new Match2(); m2.setName("boot"); //开始对上面的线程进行执行 Future<Integer> future = es.submit(m); Future<Integer> future1 = es.submit(m1); Future<Integer> future2 = es.submit(m2); Integer i = future.get(); Integer i1 = future1.get(); Integer i2 = future2.get(); System.out.println(m.getName() + "共跑了" + i + "米"); System.out.println(m1.getName() + "共跑了" + i1 + "米"); System.out.println(m2.getName() + "共跑了" + i2 + "米"); } }
最新发布
07-15
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值