Callable 如何防止 call() 返回值

有没有办法防止 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。


宝慕林4294392
浏览 221回答 1
1回答

慕神8447489

是的,将 aCountDownLatch与 count 一起使用1。CountDownLatch latch = new CountDownLatch(1);并将此闩锁传递给AxisMeasuring:public class AxisMeasuring implements SensorEventListener, Callable<List<Float>>{&nbsp; &nbsp; private CountDownLatch latch;&nbsp; &nbsp; AxisMeasuring(int _axis, final int _timeDelay, Context _context, CountDownLatch latch) {&nbsp; &nbsp; &nbsp; &nbsp; latch = latch;&nbsp; &nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public List<Float> call() throws Exception {&nbsp; &nbsp; &nbsp; &nbsp; latch.await();&nbsp; // this will get blocked until you call latch.countDown after,&nbsp; for example, a Boolean is set&nbsp; &nbsp; &nbsp; &nbsp; return values;&nbsp; &nbsp; }}在其他线程中,您可以latch.countDown()作为信号调用。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java