Callable实现多线程

此博客介绍了在Java里通过Callable接口实现多线程的方法,以龟兔赛跑为例。借助Callable接口实现多线程有能获取返回值的优点,但也存在繁琐的缺点。还给出了实现思路,包括创建Callable实现类、借助ExecutorService获取Future对象等步骤,并给出了部分代码示例。

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

package callable;

import java.util.concurrent.*;

/**

  • 龟兔赛跑例子

  • Created by lxq on 2019/7/13.

  • 通过Callable接口实现多线程

  • 优点:可以获取返回值

  • 缺点:繁琐

  • 思路:

  • 1、创建Callable实现类 + 重写call

  • 2、借助执行调度任务 ExecutorService 获取Future对象

  • ExecutorService ser = Executors.newfixedThreadPool(2);

  • Future result = ser.submit(实现类对象);

  • 3、获取值result.get();

  • 4、停止服务,ser.shutdownNow();
    */
    public class Call {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
    //创建线程
    ExecutorService ser = Executors.newFixedThreadPool(2);
    Race tortoise = new Race(“乌龟”,1000);
    Race rabbit = new Race(“兔子”,500);
    //获取值
    Future result1 = ser.submit(tortoise);
    Future result2 = ser.submit(rabbit);

     Thread.sleep(2000);//跑2秒
     tortoise.setFlag(false);//停止线程体循环
     rabbit.setFlag(false);
    
     int num1 = result1.get();
     int num2 = result2.get();
     System.out.println("乌龟跑了--》"+num1+"步");
     System.out.println("兔子跑了--》"+num2+"步");
    
     //停止服务
     ser.shutdownNow();
    

    }

}

class Race implements Callable{

private String name;//名称
private long time; //延时时间
private boolean flag = true;
private int step =0;//步

public Race(String name){
    super();
    this.name = name;
}

public Race(String name,long time){
    super();
    this.name = name;
    this.time = time;
}

@Override
public Integer call() throws Exception {
    while (flag){
        Thread.sleep(time);//延时
        step++;
    }
    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 boolean isFlag() {
    return flag;
}

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

public int getStep() {
    return step;
}

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

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值