Java Callable如何防止call()返回值
有没有一种方法可以防止call()在设置布尔值之前返回值?这样我就可以控制futureCall.get()何时完成 主要类别:Java Callable如何防止call()返回值,java,android,multithreading,callable,Java,Android,Multithreading,Callable,有没有一种方法可以防止call()在设置布尔值之前返回值?这样我就可以控制futureCall.get()何时完成 主要类别: ExecutorService executor = Executors.newCachedThreadPool(); Future<List<Float>> futureCall = executor.submit((Callable<List<Float>>) new AxisMeasuring(2,100,this)
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();
}
ExecutorService executor=Executors.newCachedThreadPool();
Future futureCall=executor.submit((可调用)new axismeasurement(2100,this));
列出这些值;
试一试{
jumpValues=futureCall.get();
}捕获(中断异常|执行异常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;
}
}
public类实现SensorEventListener,可调用{
轴测量(整数轴、最终整数时间延迟、上下文上下文){
轴=_轴;
最终上下文=_上下文;
timeDelay=_timeDelay;
handler=新的handler();
runnable=新的runnable(){
@凌驾
公开募捐{
增加(价值);
如果(!hadZeroValue&&value=12){
Log.d(“调试”,“达到点”);
}否则{
postdayed(runnable,timeDelay);
}
}
};
handler.post(可运行);
}
@凌驾
公共列表调用()引发异常{
返回值;
}
}
futureCall.get()立即返回null。是的,使用计数1
CountDownLatch latch = new CountDownLatch(1);
并将此闩锁传递给轴测量
:
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;
}
}
public类实现SensorEventListener,可调用{
私人倒计时闩锁;
轴测量(int _轴、最终int _时间延迟、上下文_上下文、倒计时闩锁){
闩锁=闩锁;
...
}
@凌驾
公共列表调用()引发异常{
latch.await();//这将被阻止,直到您在设置布尔值后调用latch.countDown
返回值;
}
}
在另一个线程中,您可以调用latch.countDown()
作为信号