Java学习提要——Callable接口

(Callable太麻烦,定位了解)
Runnable接口可以避免单继承局限,但是,Runnable接口里面的run()方法,我们不可以返回操作结果
于是,新的接口 java.util.concurrent.Callable接口
格式:

@FunctionalInterface
public interface Callable< V > {
  public V call() throws Exception ;
}//call()方法执行完线程的主题功能之后可以返回一个结果,由Callable接口定义的泛型决定
import java.util.concurrent.Callable ;

class MyThread implements Callable<String> {
    private int ticket = 10 ;
    public String call() throws Exception {
        for(int x=0 ; x < 100 ; x++ ) {
            if(this.ticket > 0) {
                System.out.println("ticket =" + this.ticket--);
            }
        }
        return "over" ;
    }
}
public class Nice {
    public static void main(String args[]) {
        //Thread类里没有发现支持Callable接口的多线程应用
    }
}

从JDK1.5开始,提供有java.util.concurrent.FutureTask< V >类主要是负责Callable接口对象操作
定义结构

public class FutureTask< V > extends Object implements RunnableFuture< V >
public interface RunnableFuture< V > extends Runnable , Future< V >

构造方法

public FutureTask(Callable< V > callable)
接收的目的只有一个,取得call()方法的返回值,通过FutureTask解决

例:

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

class MyThread implements Callable<String> {
    private int ticket = 10 ;
    public String call() throws Exception {
        for(int x=0 ; x < 100 ; x++ ) {
            if(this.ticket > 0) {
                System.out.println("ticket =" + this.ticket--);
            }
        }
        return "over" ;
    }
}
public class Nice {
    public static void main(String args[]) throws Exception {  //抛异常
        MyThread mt1 = new MyThread();
        MyThread mt2 = new MyThread();
        FutureTask<String> task1 = new FutureTask<String> (mt1) ;  //目的为了取得call()返回值
        FutureTask<String> task2 = new FutureTask<String> (mt2) ;
        //FutureTask是Runnable接口的子类,所以可以使用Thread类的构造来接收task对象
        new Thread(task1).start();  //启动多线程
        new Thread(task2).start();
        //多线程执行完毕之后可以取得内容,依靠FutureTask的父接口Future中的get()方法完成
        System.out.println("A线程的返回值" + task1.get());  //会有异常,main后面抛出
        System.out.println("B线程的返回值" + task2.get());
    }
}
//麻烦在于接收返回值信息,又要与原始的多线程实现Thread类靠拢
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值