如何在JavaFx中设置任务超时?
我有一个类,其中有一个方法可以通过usb设备获取数据并将其添加到ArrayList中:如何在JavaFx中设置任务超时?,java,multithreading,javafx,task,Java,Multithreading,Javafx,Task,我有一个类,其中有一个方法可以通过usb设备获取数据并将其添加到ArrayList中: public class usbDevice { public Task<Void> readData() { return new Task<Void>() { @Override protected Void call() throws Exception { //read da
public class usbDevice {
public Task<Void> readData() {
return new Task<Void>() {
@Override
protected Void call() throws Exception {
//read data through usb device and add it into array;
return null;
}
};
}
}
公共类usbDevice{
公共任务readData(){
返回新任务(){
@凌驾
受保护的Void调用()引发异常{
//通过usb设备读取数据并添加到阵列中;
返回null;
}
};
}
}
当按下控制器类内的按钮时,我调用此方法,该控制器类扩展了USB\U设备类:
@FXML
void readUSB(ActionEvent event) {
try {
Parent root = FXMLLoader.load(getClass().getResource("../resources/loadingPage.fxml"));
Scene scene = startButton.getScene();
root.translateXProperty().set(scene.getWidth());
parent.getChildren().add(root);
Timeline timeline = new Timeline();
KeyValue keyValue = new KeyValue(root.translateXProperty(), 0 , Interpolator.EASE_IN);
KeyFrame keyFrame = new KeyFrame(Duration.millis(100), keyValue);
timeline.getKeyFrames().add(keyFrame);
timeline.setOnFinished(event1 -> {
parent.getChildren().remove(container);
Task<Void> readTask = readData();
Thread t = new Thread(readTask);
t.start();
});
timeline.play();
} catch (IOException e) {
e.printStackTrace();
}
}
@FXML
void readUSB(ActionEvent事件){
试一试{
父根=FXMLLoader.load(getClass().getResource(“../resources/loadingPage.fxml”);
Scene-Scene=startButton.getScene();
root.translateProperty().set(scene.getWidth());
parent.getChildren().add(根目录);
时间线=新时间线();
KeyValue KeyValue=新的KeyValue(root.translateProperty(),0,Interpolator.EASE_-IN);
KeyFrame KeyFrame=新的关键帧(持续时间.millis(100),keyValue);
timeline.getKeyFrames().add(keyFrame);
timeline.setOnFinished(事件1->{
parent.getChildren().remove(容器);
任务readTask=readData();
线程t=新线程(readTask);
t、 start();
});
timeline.play();
}捕获(IOE异常){
e、 printStackTrace();
}
}
但有时我会陷入这种方法,如果在10秒后,例如,我没有获得数据,我需要重新连接到我的usb设备。我如何设置超时时间,在这个线程中每隔10秒重新连接我的usb设备,直到我通过它获取数据?
提前感谢您可以使用:
公共类USBDevice{
公共任务readData(){
返回新任务(){
@凌驾
受保护的Void调用()引发异常{
CompletableFuture=CompletableFuture.runAsync(()->{
//通过usb设备读取数据并添加到阵列中;
});
试一试{
future.get(10,时间单位:秒);
//如果读取成功,请访问此处
}捕获(中断异常ie){
Thread.currentThread().interrupt();
}捕获(被执行者){
//代码读取usb设备引发异常
}捕获(TimeoutException te){
//发生超时
}
返回null;
}
};
}
}
java命名约定
public class USBDevice {
public Task<Void> readData() {
return new Task<Void>() {
@Override
protected Void call() throws Exception {
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
//read data through usb device and add it into array;
});
try {
future.get(10, TimeUnit.SECONDS);
// get here if read was successful
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
} catch (ExecutionException ee) {
// exception was thrown by code reading usb device
} catch (TimeoutException te) {
// timeout occurred
}
return null;
}
};
}
}