简体   繁体   English

Callable 如何防止 call() 返回值

[英]Callable How to prevent call() from returning value

Is there a way to prevent call() from returning value until for example a Boolean is set?有没有办法防止 call() 在例如设置布尔值之前返回值? So that i can control when futureCall.get() is done?这样我就可以控制futureCall.get()何时完成?

Main-class:主类:

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();
}

Callable-class:可调用类:

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() returns null instantly. futureCall.get() 立即返回 null。

Yes, use a CountDownLatch with count 1 .是的,使用计数为1CountDownLatch

CountDownLatch latch = new CountDownLatch(1);

and pass this latch to AxisMeasuring :并将此闩锁传递给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;
    }
}

in other thread, you can call latch.countDown() as signal.在其他线程中,您可以调用latch.countDown()作为信号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM