通过Callable实现多线程

通过Callable实现多线程

优点:可以获取返回值,可以抛出异常(最突出的两个优点)

Callable 和 Future接口

Callable接口是类似于Runnable的接口,实现Callable接口的类和实现Runnable接口的类都是可被其他线程执行的任务。

Callable和Runnable有几点不同:

(1)Callable规定的方法是call(),Runnable规定的方法是run()

(2)call()方法可抛出异常,而run()方法是不可以抛出异常的

(3)Callable的任务执行后可返回值,运行Callable任务可拿到一个Future对象,而Runnable的任务是不能返回值的。

Future表示异步计算的结果,它提供了检查计算是否完成的方法,以等待计算的完成,并检索计算的结果,通过Future对象可了解任务执行情况,可取消任务的执行,还可获取任务的执行结果。

缺点:繁琐

思路:

(1)创建Callable对象+重写call()方法

(2)借助执行调度服务ExecutorService获取Future对象


package First.Test;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

//通过Callable接口模拟一个龟兔赛跑的例子
public class Call {
    public static void main(String[] args) {
        ExecutorService es = Executors.newFixedThreadPool(2); //开启两个线程
        
        Race tortoise = new Race("tortoise",1000); //每走一步需要1000毫秒
        
        Race rabbit = new Race("rabbit",500); //每走一步需要500毫秒
        
        Future<Integer> f1 = es.submit(tortoise); //自动在一个线程上执行

        Future<Integer> f2 = es.submit(rabbit); //自动在一个线程上执行
        

        try {
            Thread.sleep(1000 * 3);//3秒之后
            tortoise.setFlag(false);
            rabbit.setFlag(false);
            
            System.out.println("tortoise move all step : " + f1.get());
            System.out.println("rabbit move all step : " + f2.get());
            
            es.shutdown(); //关闭调度器,这一步尤为重要,不关会一直耗损内存
            
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
        catch (ExecutionException e) {
            e.printStackTrace();
        } 
        
        
    }    
    
    

}


class Race implements Callable<Integer>{
    
    private String name; //参赛者名称
    
    private long time; //参赛者每走一步需要花的时间
    
    private int step; //参赛者总共走了多少步
    
    private boolean flag = true; //比较时间是否结束 默认为未结束
    
    public Race(){}
    
    public Race(String name, long time){
        this.name = name;
        this.time = time;
    }
    
    @Override
    public Integer call() throws Exception {
        
        while(flag){
            Thread.sleep(time); //模拟参赛者走一步需要花的时长
            step++; //比赛时间尚未结束,步数加1
        }
        
        return step; //一共走了多少步
    }
    
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public long getTime() {
        return time;
    }

    public void setTime(long time) {
        this.time = time;
    }

    public int getStep() {
        return step;
    }

    public void setStep(int step) {
        this.step = step;
    }

    public boolean isFlag() {
        return flag;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }
    
}

运行结果:

tortoise move all step : 3
rabbit move all step : 6

在 Java 中,可以通过实现 Callable 接口,实现多线程操作。Callable 接口与 Runnable 接口类似,都是用来实现多线程操作的接口。但是,Callable 接口支持返回结果和抛出异常。 下面是一个简单的示例,演示如何使用 Callable 实现多线程操作: ``` import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class MyCallable implements Callable<String> { private String name; public MyCallable(String name) { this.name = name; } @Override public String call() throws Exception { System.out.println("Thread " + name + " is running..."); Thread.sleep(5000); return "Hello from thread " + name; } public static void main(String[] args) throws Exception { ExecutorService executorService = Executors.newFixedThreadPool(3); Future<String> result1 = executorService.submit(new MyCallable("Thread-1")); Future<String> result2 = executorService.submit(new MyCallable("Thread-2")); Future<String> result3 = executorService.submit(new MyCallable("Thread-3")); System.out.println(result1.get()); System.out.println(result2.get()); System.out.println(result3.get()); executorService.shutdown(); } } ``` 在上面的示例中,我们创建了一个实现Callable 接口的类 MyCallable。在 call() 方法中,我们输出了当前线程的名称,然后让线程休眠 5 秒,最后返回一个字符串。 在 main() 方法中,我们创建了一个 ExecutorService,并向其提交了三个 MyCallable 对象。ExecutorService.submit() 方法会返回一个 Future 对象,可以使用 get() 方法获取 MyCallable 对象的返回值。最后,我们关闭了 ExecutorService。 执行上面的代码,可以看到如下输出: ``` Thread Thread-1 is running... Thread Thread-2 is running... Thread Thread-3 is running... Hello from thread Thread-1 Hello from thread Thread-2 Hello from thread Thread-3 ``` 从输出结果可以看出,我们创建的三个线程都在运行,而且每个线程都在休眠 5 秒钟。而且,我们使用 Future 对象获取了每个线程的返回值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值