为了账号安全,请及时绑定邮箱和手机立即绑定

Callable 如何防止 call() 返回值

Callable 如何防止 call() 返回值

宝慕林4294392 2021-08-25 16:17:16
有没有办法防止 call() 在例如设置布尔值之前返回值?这样我就可以控制futureCall.get()何时完成?主类:ExecutorService executor = Executors.newCachedThreadPool();Future<List<Float>> futureCall = executor.submit((Callable<List<Float>>) new AxisMeasuring(2,100,this));List<Float> jumpValues;try {    jumpValues = futureCall.get();} catch (InterruptedException | ExecutionException e) {    e.printStackTrace();}可调用类:public class AxisMeasuring implements SensorEventListener, Callable<List<Float>>{    AxisMeasuring(int _axis, final int _timeDelay, Context _context) {        axis = _axis;        final Context context = _context;        timeDelay = _timeDelay;        handler = new Handler();        runnable = new Runnable() {            @Override            public void run() {                values.add(value);                if (!hadZeroValue && value <= 1) {                    hadZeroValue = true;                }                if (hadZeroValue && value >= 12) {                    Log.d("Debug","Point reached");                } else {                    handler.postDelayed(runnable, timeDelay);                }            }        };        handler.post(runnable);    }    @Override    public List<Float> call() throws Exception {        return values;    }}futureCall.get() 立即返回 null。
查看完整描述

1 回答

?
慕神8447489

TA贡献1780条经验 获得超1个赞

是的,将 aCountDownLatch与 count 一起使用1。


CountDownLatch latch = new CountDownLatch(1);

并将此闩锁传递给AxisMeasuring:


public class AxisMeasuring implements SensorEventListener, Callable<List<Float>>{


    private CountDownLatch latch;


    AxisMeasuring(int _axis, final int _timeDelay, Context _context, CountDownLatch latch) {

        latch = latch;

        ...

    }


    @Override

    public List<Float> call() throws Exception {

        latch.await();  // this will get blocked until you call latch.countDown after,  for example, a Boolean is set

        return values;

    }

}

在其他线程中,您可以latch.countDown()作为信号调用。


查看完整回答
反对 回复 2021-08-25
  • 1 回答
  • 0 关注
  • 220 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信