簡體   English   中英

Callable 如何防止 call() 返回值

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

有沒有辦法防止 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。

是的,使用計數為1CountDownLatch

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()作為信號。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM