javafx:如何停止对象';当对象本身从可观察列表中删除时,正在运行的后台任务?
我有一个javafx:如何停止对象';当对象本身从可观察列表中删除时,正在运行的后台任务?,java,javafx,Java,Javafx,我有一个Trade对象,每当构建它时,它都会在后台启动一个任务(比如说download currentPrice),并开始每10秒运行一次 创建交易对象时,它也会添加到可观察列表 问题:当我从ObservableList中删除对象时,我可以看到任务(下载currentPrice)仍在后台运行,尽管对象不再位于ObservableList中 该对象是否已实际删除 当对象本身已从ObservableList中删除时,如何停止对象的后台任务运行? 我的目标是永远删除对象,并停止其后台任务的运行 pub
Trade
对象,每当构建它时,它都会在后台启动一个任务(比如说download currentPrice),并开始每10秒运行一次
创建交易
对象时,它也会添加到可观察列表
问题:当我从ObservableList中删除对象时,我可以看到任务(下载currentPrice)仍在后台运行,尽管对象不再位于ObservableList
中
public class Trade{
....
private final ScheduledService<Number> priceService = new ScheduledService<Number>() {
@Override
public Task<Number> createTask(){
return new Task<Number>() {
@Override
public Number call() throws InterruptedException, IOException {
return getCurrentPriceFromGoogleFinance();
}
};
}
};
public Trade(){
priceService.setPeriod(Duration.seconds(10));
priceService.setOnFailed(e -> priceService.getException().printStackTrace());
this.currentPrice = new ReadOnlyDoubleWrapper(0);
this.currentPrice.bind(priceService.lastValueProperty());
startMonitoring();
}
public ReadOnlyDoubleProperty currentPriceProperty(){
return this.currentPrice.getReadOnlyProperty();
}
public final double getCurrentPrice(){
return currentPriceProperty().get();
}
// multi-threading
public final void startMonitoring() {
priceService.restart();
}
public final void stopMonitoring() {
priceService.cancel();
}
....
}
公共级贸易{
....
private final ScheduledService priceService=新ScheduledService(){
@凌驾
公共任务createTask(){
返回新任务(){
@凌驾
public Number call()引发InterruptedException,IOException{
从Google Finance()返回GetCurrentPrice;
}
};
}
};
公共贸易(){
priceService.setPeriod(持续时间.秒(10));
priceService.setOnFailed(e->priceService.getException().printStackTrace());
this.currentPrice=新的ReadOnlyDoubleWrapper(0);
this.currentPrice.bind(priceService.lastValueProperty());
开始监视();
}
public ReadOnlyDoubleProperty currentPriceProperty(){
返回此.currentPrice.getReadOnlyProperty();
}
公共最终双getCurrentPrice(){
返回currentPriceProperty().get();
}
//多线程
公共最终作废开始监控(){
priceService.restart();
}
公共最终失效监测(){
priceService.cancel();
}
....
}
如果我对垃圾收集器的理解是正确的,那么即使从列表中删除对象,它在被收集之前也会存在一段时间
要停止任务,请将添加到可观察列表中。您可以删除Trade
并在其上调用stopMonitoring()
。这可能有希望停止这项任务