Spec-Zone .ru
спецификации, руководства, описания, API
|
public abstract class Task<V> extends java.util.concurrent.FutureTask<V> implements Worker<V>, EventTarget
Полностью заметная реализация a FutureTask
. Задачи представляют дополнительное состояние и заметные свойства, полезные для программирования асинхронных задач в JavaFX, как определено в Worker
интерфейс. Реализация Задачи должна переопределить call()
метод. Этот метод вызывается на фоновый поток. Любое состояние, которое используется в этом методе, должно быть безопасно читать и записать из фонового потока. Например, управление живым графиком сцены от этого метода опасно и приведет к исключениям на этапе выполнения.
Задачи гибки и чрезвычайно полезны для инкапсуляции "работы". Поскольку Service
разрабатывается, чтобы выполнить Задачу, любые Задачи, определенные приложением или кодом библиотеки, могут легко использоваться со Службой. Аналогично, так как Задача расширяется от FutureTask, это является очень легким и естественным использовать Задачу с параллелизмом java Executor
API. Так как Задача Выполнима, можно также вызвать ее непосредственно (вызывая FutureTask.run()
метод) от другого фонового потока. Это учитывает состав работы, или передайте это к новому потоку, созданному и выполняемому вручную. Наконец, так как можно вручную создать новый поток, передавая это Выполнимое, возможно использовать следующую идиому:
Thread th = new Thread(task);
th.setDaemon(true);
th.start();
Отметьте что это кодовые наборы флаг демона Потока к истине. Если бы Вы хотите, чтобы фоновый поток предотвратил VM от существующего после того, как последняя стадия закрывается, то Вы хотели бы, чтобы демон был ложью. Однако, если Вы хотите, чтобы фоновые потоки просто завершились после того, как все этапы закрываются, тогда следует установить демона в истину.
Хотя ExecutorService
определяет несколько методов, которые берут Выполнимое, следует обычно ограничить себя использованием execute
метод, наследованный от Executor
.
Как с FutureTask, Задача является class с одним выстрелом и не может быть снова использована. См. Service
для допускающего повторное использование Worker
.
Поскольку Задача разрабатывается для использования с приложениями GUI JavaFX, это гарантирует, что каждое изменение к его общедоступным свойствам, так же как уведомления об изменении для состояния, ошибок, и для обработчиков событий, все происходят на основном потоке приложения JavaFX. Доступ к этим свойствам от фонового потока (включая call()
метод), приведет к повышаемым исключениям на этапе выполнения.
Это строго поощряется, что все Задачи инициализируются с неизменным состоянием, на которое будет работать Задача. Это должно быть сделано, предоставляя конструктору Задачи, который берет параметры, необходимые для выполнения Задачи. Неизменное состояние облегчает и безопасный использовать от любого потока и гарантирует правильность в присутствии многократных потоков.
В Java нет никакого надежного способа "уничтожить" поток в процессе. Однако, когда cancel
вызывается на Задаче, важно что обработка остановки Задачи. "Безудержная" Задача могла бы продолжать обрабатывать и обновлять сообщение, текст, и свойства продвижения даже после того, как Задача была отменена! В Java, отменяя Задачу совместное усилие. Пользователь Задачи запросит, чтобы она была отменена, и автор Задачи должен проверить, является ли, был отменен в пределах тела call
метод. Есть два способа, которыми это может быть сделано. Во-первых, автор Задачи может проверить isCancelled метод, наследованный от FutureTask
, видеть, была ли Задача отменена. Во-вторых, если реализация Задачи использует какие-либо вызовы блокирования (такие как NIO InterruptibleChannels или Thread.sleep), и задача отменяется, в то время как в таком вызове блокирования, InterruptedException бросается. Реализации задачи, у которых есть вызовы блокирования, должны распознать, что прерванный поток может быть сигналом для отмененной задачи и должен проверить isCancelled метод дважды, чтобы гарантировать, что InterruptedException был брошен из-за отмены Задачи.
Следующий набор примеров демонстрирует некоторые из наиболее популярных способов использования Задач.
Первым примером является простой цикл, который не делает ничего особенно полезного, но демонстрирует фундаментальные аспекты записи Задачи правильно. Этот пример просто циклично выполнит и напечатает к стандарту на каждой итерации цикла. Когда это завершается, это возвращает число раз, которого это выполнило итерации.
Task<Integer> task = new Task<Integer>() {
@Override protected Integer call() throws Exception {
int iterations;
for (iterations = 0; iterations < 100000; iterations++) {
if (isCancelled()) {
break;
}
System.out.println("Iteration " + iterations);
}
return iterations;
}
};
Во-первых, мы определяем, какое значение возвращается из этой Задачи. В этом случае мы хотим возвратить число раз, которого мы выполнили итерации, таким образом, мы определим Задачу быть Целого числа типа при использовании обобщений. Затем, в пределах реализации call
метод, мы выполняем итерации от 0 до 100000. На каждой итерации мы проверяем, чтобы видеть, была ли эта Задача отменена. Если это было, то мы убегаем из цикла и возвращаем число раз, которого мы выполнили итерации. Иначе сообщение печатается к консоли и итеративному увеличенному количеству, и мы продолжаем цикличное выполнение.
Проверка isCancelled () в теле цикла является критической, иначе разработчик может отменить задачу, но задача будет продолжать выполнять и обновлять и продвижение и возвращать неправильное следствие конца call
метод. Корректная реализация Задачи будет всегда проверять на отмену.
Подобный предыдущему примеру, кроме этого времени мы изменим продвижение Задачи в каждой итерации. Отметьте, что у нас есть выбор сделать в случае отмены. Мы хотим задержать продвижение к-1 (неопределенный), когда Задача отменяется, или мы хотим оставить продвижение, где это было в? В этом случае, позволяет, оставляют продвижение в покое и только обновляют сообщение на отмене, хотя обновляя продвижение после того, как отмена является совершенно допустимым выбором.
Task<Integer> task = new Task<Integer>() {
@Override protected Integer call() throws Exception {
int iterations;
for (iterations = 0; iterations < 10000000; iterations++) {
if (isCancelled()) {
updateMessage("Cancelled");
break;
}
updateMessage("Iteration " + iterations);
updateProgress(iterations, 10000000);
}
return iterations;
}
};
Как прежде, в пределах для цикла мы проверяем, была ли Задача отменена. Если это было отменено, мы обновим сообщение Задачи, чтобы указать, что это было отменено, и затем повреждается как прежде. Если Задача не была отменена, то мы обновим ее сообщение, чтобы указать на текущую итерацию и затем обновить продвижение, чтобы указать на текущее продвижение.
Этот пример добавляет к предыдущим примерам вызов блокирования. Поскольку вызов блокирования может брошенный InterruptedException, и потому что InterruptedException может произойти в результате отменяемой Задачи, мы должны убедиться, что обработали InterruptedException и проверили состояние отмены.
Task<Integer> task = new Task<Integer>() {
@Override protected Integer call() throws Exception {
int iterations;
for (iterations = 0; iterations < 1000; iterations++) {
if (isCancelled()) {
updateMessage("Cancelled");
break;
}
updateMessage("Iteration " + iterations);
updateProgress(iterations, 1000);
// Now block the thread for a short time, but be sure
// to check the interrupted exception for cancellation!
try {
Thread.sleep(100);
} catch (InterruptedException interrupted) {
if (isCancelled()) {
updateMessage("Cancelled");
break;
}
}
}
return iterations;
}
};
Здесь мы добавили к телу цикла a Thread.sleep
вызвать. Так как это - вызов блокирования, я должен обработать потенциальный InterruptedException. В пределах блока выгоды я проверю, была ли Задача отменена, и если так, обновляет сообщение соответственно и убегает из цикла.
Большинство Задач требует некоторых параметров, чтобы сделать полезную работу. Например, DeleteRecordTask нуждается в объектном или первичном ключе, чтобы удалить из базы данных. ReadFileTask нуждается в URI файла, который будет считан. Поскольку Задачи работают на фоновом потоке, забота должна быть проявлена, чтобы удостовериться тело call
метод не читает или изменяет общее состояние. Есть два метода, самые полезные для выполнения этого: использование заключительных переменных, и передача переменных к Задаче во время конструкции.
При использовании Задачи как анонимный class самый естественный способ передать параметры к Задаче при использовании заключительных переменных. В этом примере мы передаем к Задаче общее количество времен, которых должна выполнить итерации Задача.
final int totalIterations = 9000000;
Task<Integer> task = new Task<Integer>() {
@Override protected Integer call() throws Exception {
int iterations;
for (iterations = 0; iterations < totalIterations; iterations++) {
if (isCancelled()) {
updateMessage("Cancelled");
break;
}
updateMessage("Iteration " + iterations);
updateProgress(iterations, totalIterations);
}
return iterations;
}
};
С тех пор totalIterations
является заключительным, call
метод может безопасно считать это и обратиться к этому от фонового потока.
Когда библиотеки задачи записи (в противоположность реализациям определенного использования), мы должны использовать различный метод. В этом случае я создам IteratingTask, который выполняет ту же самую работу как выше. На сей раз, так как IteratingTask определяется в его собственном файле, ему должны будут передать параметры к этому в его конструкторе. Эти параметры присваиваются заключительным переменным.
public class IteratingTask extends Task<Integer> {
private final int totalIterations;
public IteratingTask(int totalIterations) {
this.totalIterations = totalIterations;
}
@Override protected Integer call() throws Exception {
int iterations = 0;
for (iterations = 0; iterations < totalIterations; iterations++) {
if (isCancelled()) {
updateMessage("Cancelled");
break;
}
updateMessage("Iteration " + iterations);
updateProgress(iterations, totalIterations);
}
return iterations;
}
}
И затем когда использующийся:
IteratingTask task = new IteratingTask(8000000);
Таким образом параметры передают к IteratingTask безопасным способом, и снова, являются заключительными. Таким образом, call
метод может безопасно считать это состояние из фонового потока.
ПРЕДУПРЕЖДЕНИЕ: не передавайте изменчивое состояние к Задаче и затем работайте на нем от фонового потока. Выполнение так может представить условия состязания. В частности предположите, что у Вас был SaveCustomerTask, который взял Клиента в его конструкторе. Хотя у SaveCustomerTask может быть заключительная ссылка на Клиента, если Потребительский объект изменчив, то возможно, что и SaveCustomerTask и некоторый другой код программы будут читать или изменять состояние Клиента от различных потоков. Будьте очень осторожны в таких случаях, что, в то время как изменчивый объект, такой как этот Клиент используется от фонового потока, что он не используется также от другого потока. В частности если фоновый поток читает данные из базы данных и обновляет Потребительский объект, и Потребительский объект связывается с узлами графика сцены (такими как средства управления UI), то могло быть нарушение поточной обработки правил! Для таких случаев измените Потребительский объект от Потока Приложения FX, а не от фонового потока.
public class UpdateCustomerTask extends Task<Customer> {
private final Customer customer;
public UpdateCustomerTask(Customer customer) {
this.customer = customer;
}
@Override protected Customer call() throws Exception {
// pseudo-code:
// query the database
// read the values
// Now update the customer
Platform.runLater(new Runnable() {
@Override public void run() {
customer.setF setFirstName(rs.getString("FirstName"));
// etc
}
});
return customer;
}
}
Многие, если вообще, Задачи должны возвратить значение после завершения. Для Задач CRUD можно было бы ожидать, что "Создать" Задача возвратит недавно создаваемый объектный или первичный ключ, Задача "Чтения" возвратила бы объект чтения, задача "Обновления" возвратит число записей, обновленных, и "Удалить" задача возвратила бы число удаленных записей.
Однако иногда только нет ничего действительно полезного, чтобы возвратиться. Например, у меня могла бы быть Задача, которая пишет в файл. Задача встроила в это механизм для того, чтобы указать, успешно выполнилось ли это или перестало работать наряду с числом записанных байтов (продвижение), и таким образом нет ничего действительно для меня, чтобы возвратиться. В таком случае можно использовать Пустой тип. Это - специальный тип на языке Java, который может только быть присвоен значение null
. Вы использовали бы это следующим образом:
final String filePath = "/foo.txt";
final String contents = "Some contents";
Task<Void> task = new Task<Void>() {
@Override protected Void call() throws Exception {
File file = new File(filePath);
FileOutputStream out = new FileOutputStream(file);
// ... and other code to write the contents ...
// Return null at the end of a Task of type Void
return null;
}
};
Поскольку ListView, TableView, и другие средства управления UI и узлы графика сцены используют ObservableList, распространено хотеть создать и возвратить ObservableList из Задачи. Когда Вы не хотите вывести на экран промежуточные значения, самый легкий способ правильно записать, что такая Задача состоит в том, чтобы просто создать ObservableList в пределах call
метод, и затем возвращает это в конце Задачи.
Task<ObservableList<Rectangle>> task = new Task<ObservableList<Rectangle>>() {
@Override protected ObservableList<Rectangle> call() throws Exception {
updateMessage("Creating Rectangles");
ObservableList<Rectangle> results = FXCollections.observableArrayList();
for (int i=0; i<100; i++) {
if (isCancelled()) break;
Rectangle r = new Rectangle(10, 10);
r.setX(10 * i);
results.add(r);
updateProgress(i, 100);
}
return results;
}
};
In the above example, we are going to create 100 rectangles and return them from this task. An ObservableList is created within the call
method, populated, and then returned.
Sometimes you want to create a Task which will return partial results. Perhaps you are building a complex scene graph and want to show the scene graph as it is being constructed. Or perhaps you are reading a large amount of data over the network and want to display the entries in a TableView as the data is arriving. In such cases, there is some shared state available both to the FX Application Thread and the background thread. Great care must be taken to never update shared state from any thread other than the FX Application Thread.
The easiest way to do this is to expose a new property on the Task which will represent the partial result. Then make sure to use Platform.runLater
when adding new items to the partial result.
public class PartialResultsTask extends Task<ObservableList<Rectangle>> {
// Uses Java 7 diamond operator
private ReadOnlyObjectWrapper> partialResults =
new ReadOnlyObjectWrapper<>(this, "partialResults",
FXCollections.observableArrayList(new ArrayList()));
public final ObservableList getPartialResults() { return partialResults.get(); }
public final ReadOnlyObjectProperty> partialResultsProperty() {
return partialResults.getReadOnlyProperty();
}
@Override protected ObservableList call() throws Exception {
updateMessage("Creating Rectangles...");
for (int i=0; i<100; i++) {
if (isCancelled()) break;
final Rectangle r = new Rectangle(10, 10);
r.setX(10 * i);
Platform.runLater(new Runnable() {
@Override public void run() {
partialResults.get().add(r);
}
});
updateProgress(i, 100);
}
return partialResults.get();
}
}
Generally, Tasks should not interact directly with the UI. Doing so creates a tight coupling between a specific Task implementation and a specific part of your UI. However, when you do want to create such a coupling, you must ensure that you use Platform.runLater
so that any modifications of the scene graph occur on the FX Application Thread.
final Group group = new Group();
Task<Void> task = new Task<Void>() {
@Override protected Void call() throws Exception {
for (int i=0; i<100; i++) {
if (isCancelled()) break;
final Rectangle r = new Rectangle(10, 10);
r.setX(10 * i);
Platform.runLater(new Runnable() {
@Override public void run() {
group.getChildren().add(r);
}
});
}
return null;
}
};
Sometimes you may want to write a Task which updates its progress, message, text, or in some other way reacts whenever a state change happens on the Task. For example, you may want to change the status message on the Task on Failure, Success, Running, or Cancelled state changes.
Task<Integer> task = new Task<Integer>() {
@Override protected Integer call() throws Exception {
int iterations = 0;
for (iterations = 0; iterations < 100000; iterations++) {
if (isCancelled()) {
break;
}
System.out.println("Iteration " + iterations);
}
return iterations;
}
@Override protected void succeeded() {
super.succeeded();
updateMessage("Done!");
}
@Override protected void cancelled() {
super.cancelled();
updateMessage("Cancelled!");
}
@Override protected void failed() {
super.failed();
updateMessage("Failed!");
}
};
Type | Property and Description |
---|---|
ReadOnlyObjectProperty<java.lang.Throwable> |
исключение
Gets the ReadOnlyObjectProperty representing any exception which occurred.
|
ReadOnlyStringProperty |
сообщение
Gets the ReadOnlyStringProperty representing the message.
|
ObjectProperty<EventHandler<WorkerStateEvent>> |
onCancelled
The onCancelled event handler is called whenever the Task state transitions to the CANCELLED state.
|
ObjectProperty<EventHandler<WorkerStateEvent>> |
onFailed
The onFailed event handler is called whenever the Task state transitions to the FAILED state.
|
ObjectProperty<EventHandler<WorkerStateEvent>> |
onRunning
The onRunning event handler is called whenever the Task state transitions to the RUNNING state.
|
ObjectProperty<EventHandler<WorkerStateEvent>> |
onScheduled
The onSchedule event handler is called whenever the Task state transitions to the SCHEDULED state.
|
ObjectProperty<EventHandler<WorkerStateEvent>> |
onSucceeded
The onSucceeded event handler is called whenever the Task state transitions to the SUCCEEDED state.
|
ReadOnlyDoubleProperty |
продвижение
Gets the ReadOnlyDoubleProperty representing the progress.
|
ReadOnlyBooleanProperty |
выполнение
Gets the ReadOnlyBooleanProperty representing whether the Worker is running.
|
ReadOnlyObjectProperty<Worker.State> |
состояние
Gets the ReadOnlyObjectProperty representing the current state.
|
ReadOnlyStringProperty |
title
Gets the ReadOnlyStringProperty representing the title.
|
ReadOnlyDoubleProperty |
totalWork
Gets the ReadOnlyDoubleProperty representing the maximum amount of work that needs to be done.
|
ReadOnlyObjectProperty<V> |
значение
Gets the ReadOnlyObjectProperty representing the value.
|
ReadOnlyDoubleProperty |
workDone
Gets the ReadOnlyDoubleProperty representing the current progress.
|
Рабочий. Государство
Constructor and Description |
---|
Task()
Creates a new Task.
|
Modifier and Type | Method and Description |
---|---|
<T extends Event> |
addEventFilter(EventType<T> eventType, EventHandler<? super T> eventFilter)
Registers an event filter to this task.
|
<T extends Event> |
addEventHandler(EventType<T> eventType, EventHandler<? super T> eventHandler)
Registers an event handler to this task.
|
EventDispatchChain |
buildEventDispatchChain(EventDispatchChain tail)
Construct an event dispatch chain for this target.
|
protected abstract V |
call()
Invoked when the Task is executed, the call method must be overridden and implemented by subclasses.
|
boolean |
cancel()
Terminates execution of this Worker.
|
boolean |
cancel(boolean mayInterruptIfRunning) |
protected void |
cancelled()
A protected convenience method for subclasses, called whenever the state of the Task has transitioned to the CANCELLED state.
|
ReadOnlyObjectProperty<java.lang.Throwable> |
exceptionProperty()
Gets the ReadOnlyObjectProperty representing any exception which occurred.
|
protected void |
failed()
A protected convenience method for subclasses, called whenever the state of the Task has transitioned to the FAILED state.
|
void |
fireEvent(Event event)
Fires the specified event.
|
java.lang.Throwable |
getException()
Gets the value of the property exception.
|
java.lang.String |
getMessage()
Gets the value of the property message.
|
EventHandler<WorkerStateEvent> |
getOnCancelled()
The onCancelled event handler is called whenever the Task state transitions to the CANCELLED state.
|
EventHandler<WorkerStateEvent> |
getOnFailed()
The onFailed event handler is called whenever the Task state transitions to the FAILED state.
|
EventHandler<WorkerStateEvent> |
getOnRunning()
The onRunning event handler is called whenever the Task state transitions to the RUNNING state.
|
EventHandler<WorkerStateEvent> |
getOnScheduled()
The onSchedule event handler is called whenever the Task state transitions to the SCHEDULED state.
|
EventHandler<WorkerStateEvent> |
getOnSucceeded()
The onSucceeded event handler is called whenever the Task state transitions to the SUCCEEDED state.
|
double |
getProgress()
Gets the value of the property progress.
|
Рабочий. Государство |
getState()
Gets the value of the property state.
|
java.lang.String |
getTitle()
Gets the value of the property title.
|
double |
getTotalWork()
Gets the value of the property totalWork.
|
V |
getValue()
Gets the value of the property value.
|
double |
getWorkDone()
Gets the value of the property workDone.
|
boolean |
isRunning()
Gets the value of the property running.
|
ReadOnlyStringProperty |
messageProperty()
Gets the ReadOnlyStringProperty representing the message.
|
ObjectProperty<EventHandler<WorkerStateEvent>> |
onCancelledProperty()
The onCancelled event handler is called whenever the Task state transitions to the CANCELLED state.
|
ObjectProperty<EventHandler<WorkerStateEvent>> |
onFailedProperty()
The onFailed event handler is called whenever the Task state transitions to the FAILED state.
|
ObjectProperty<EventHandler<WorkerStateEvent>> |
onRunningProperty()
The onRunning event handler is called whenever the Task state transitions to the RUNNING state.
|
ObjectProperty<EventHandler<WorkerStateEvent>> |
onScheduledProperty()
The onSchedule event handler is called whenever the Task state transitions to the SCHEDULED state.
|
ObjectProperty<EventHandler<WorkerStateEvent>> |
onSucceededProperty()
The onSucceeded event handler is called whenever the Task state transitions to the SUCCEEDED state.
|
ReadOnlyDoubleProperty |
progressProperty()
Gets the ReadOnlyDoubleProperty representing the progress.
|
<T extends Event> |
removeEventFilter(EventType<T> eventType, EventHandler<? super T> eventFilter)
Unregisters a previously registered event filter from this task.
|
<T extends Event> |
removeEventHandler(EventType<T> eventType, EventHandler<? super T> eventHandler)
Unregisters a previously registered event handler from this task.
|
protected void |
running()
A protected convenience method for subclasses, called whenever the state of the Task has transitioned to the RUNNING state.
|
ReadOnlyBooleanProperty |
runningProperty()
Gets the ReadOnlyBooleanProperty representing whether the Worker is running.
|
protected void |
scheduled()
A protected convenience method for subclasses, called whenever the state of the Task has transitioned to the SCHEDULED state.
|
protected <T extends Event> |
setEventHandler(EventType<T> eventType, EventHandler<? super T> eventHandler)
Sets the handler to use for this event type.
|
void |
setOnCancelled(EventHandler<WorkerStateEvent> value)
The onCancelled event handler is called whenever the Task state transitions to the CANCELLED state.
|
void |
setOnFailed(EventHandler<WorkerStateEvent> value)
The onFailed event handler is called whenever the Task state transitions to the FAILED state.
|
void |
setOnRunning(EventHandler<WorkerStateEvent> value)
The onRunning event handler is called whenever the Task state transitions to the RUNNING state.
|
void |
setOnScheduled(EventHandler<WorkerStateEvent> value)
The onSchedule event handler is called whenever the Task state transitions to the SCHEDULED state.
|
void |
setOnSucceeded(EventHandler<WorkerStateEvent> value)
The onSucceeded event handler is called whenever the Task state transitions to the SUCCEEDED state.
|
ReadOnlyObjectProperty<Worker.State> |
stateProperty()
Gets the ReadOnlyObjectProperty representing the current state.
|
protected void |
succeeded()
A protected convenience method for subclasses, called whenever the state of the Task has transitioned to the SUCCEEDED state.
|
ReadOnlyStringProperty |
titleProperty()
Gets the ReadOnlyStringProperty representing the title.
|
ReadOnlyDoubleProperty |
totalWorkProperty()
Gets the ReadOnlyDoubleProperty representing the maximum amount of work that needs to be done.
|
protected void |
updateMessage(java.lang.String message)
Updates the
message property. |
protected void |
updateProgress(double workDone, double max)
Updates the
workDone , totalWork , and progress properties. |
protected void |
updateProgress(long workDone, long max)
Updates the
workDone , totalWork , and progress properties. |
protected void |
updateTitle(java.lang.String title)
Updates the
title property. |
ReadOnlyObjectProperty<V> |
valueProperty()
Gets the ReadOnlyObjectProperty representing the value.
|
ReadOnlyDoubleProperty |
workDoneProperty()
Gets the ReadOnlyDoubleProperty representing the current progress.
|
public final ReadOnlyObjectProperty<Worker.State> stateProperty
stateProperty
in interface Worker<V>
getState()
public final ObjectProperty<EventHandler<WorkerStateEvent>> onScheduledProperty
getOnScheduled()
, setOnScheduled(EventHandler)
public final ObjectProperty<EventHandler<WorkerStateEvent>> onRunningProperty
getOnRunning()
, setOnRunning(EventHandler)
public final ObjectProperty<EventHandler<WorkerStateEvent>> onSucceededProperty
getOnSucceeded()
, setOnSucceeded(EventHandler)
public final ObjectProperty<EventHandler<WorkerStateEvent>> onCancelledProperty
getOnCancelled()
, setOnCancelled(EventHandler)
public final ObjectProperty<EventHandler<WorkerStateEvent>> onFailedProperty
getOnFailed()
, setOnFailed(EventHandler)
public final ReadOnlyObjectProperty<V> valueProperty
valueProperty
in interface Worker<V>
getValue()
public final ReadOnlyObjectProperty<java.lang.Throwable> exceptionProperty
exceptionProperty
in interface Worker<V>
getException()
public final ReadOnlyDoubleProperty workDoneProperty
workDoneProperty
in interface Worker<V>
getWorkDone()
public final ReadOnlyDoubleProperty totalWorkProperty
totalWorkProperty
in interface Worker<V>
getTotalWork()
public final ReadOnlyDoubleProperty progressProperty
progressProperty
in interface Worker<V>
getProgress()
public final ReadOnlyBooleanProperty runningProperty
runningProperty
in interface Worker<V>
isRunning()
public final ReadOnlyStringProperty messageProperty
messageProperty
in interface Worker<V>
getMessage()
public final ReadOnlyStringProperty titleProperty
titleProperty
in interface Worker<V>
getTitle()
protected abstract V call() throws java.lang.Exception
java.lang.Exception
- an unhandled exception which occurred during the background operationpublic final Worker.State getState()
public final ReadOnlyObjectProperty<Worker.State> stateProperty()
Worker
stateProperty
in interface Worker<V>
getState()
public final ObjectProperty<EventHandler<WorkerStateEvent>> onScheduledProperty()
getOnScheduled()
, setOnScheduled(EventHandler)
public final EventHandler<WorkerStateEvent> getOnScheduled()
public final void setOnScheduled(EventHandler<WorkerStateEvent> value)
value
- the event handler, can be null to clear itprotected void scheduled()
public final ObjectProperty<EventHandler<WorkerStateEvent>> onRunningProperty()
getOnRunning()
, setOnRunning(EventHandler)
public final EventHandler<WorkerStateEvent> getOnRunning()
public final void setOnRunning(EventHandler<WorkerStateEvent> value)
value
- the event handler, can be null to clear itprotected void running()
public final ObjectProperty<EventHandler<WorkerStateEvent>> onSucceededProperty()
getOnSucceeded()
, setOnSucceeded(EventHandler)
public final EventHandler<WorkerStateEvent> getOnSucceeded()
public final void setOnSucceeded(EventHandler<WorkerStateEvent> value)
value
- the event handler, can be null to clear itprotected void succeeded()
public final ObjectProperty<EventHandler<WorkerStateEvent>> onCancelledProperty()
getOnCancelled()
, setOnCancelled(EventHandler)
public final EventHandler<WorkerStateEvent> getOnCancelled()
public final void setOnCancelled(EventHandler<WorkerStateEvent> value)
value
- the event handler, can be null to clear itprotected void cancelled()
public final ObjectProperty<EventHandler<WorkerStateEvent>> onFailedProperty()
getOnFailed()
, setOnFailed(EventHandler)
public final EventHandler<WorkerStateEvent> getOnFailed()
public final void setOnFailed(EventHandler<WorkerStateEvent> value)
value
- the event handler, can be null to clear itprotected void failed()
public final V getValue()
public final ReadOnlyObjectProperty<V> valueProperty()
Worker
valueProperty
in interface Worker<V>
getValue()
public final java.lang.Throwable getException()
getException
in interface Worker<V>
public final ReadOnlyObjectProperty<java.lang.Throwable> exceptionProperty()
Worker
exceptionProperty
in interface Worker<V>
getException()
public final double getWorkDone()
getWorkDone
in interface Worker<V>
Worker.totalWorkProperty()
, Worker.progressProperty()
public final ReadOnlyDoubleProperty workDoneProperty()
Worker
workDoneProperty
in interface Worker<V>
getWorkDone()
public final double getTotalWork()
getTotalWork
in interface Worker<V>
Worker.workDoneProperty()
, Worker.progressProperty()
public final ReadOnlyDoubleProperty totalWorkProperty()
Worker
totalWorkProperty
in interface Worker<V>
getTotalWork()
public final double getProgress()
getProgress
in interface Worker<V>
Worker.workDoneProperty()
, Worker.totalWorkProperty()
public final ReadOnlyDoubleProperty progressProperty()
Worker
progressProperty
in interface Worker<V>
getProgress()
public final boolean isRunning()
public final ReadOnlyBooleanProperty runningProperty()
Worker
runningProperty
in interface Worker<V>
isRunning()
public final java.lang.String getMessage()
getMessage
in interface Worker<V>
public final ReadOnlyStringProperty messageProperty()
Worker
messageProperty
in interface Worker<V>
getMessage()
public final java.lang.String getTitle()
public final ReadOnlyStringProperty titleProperty()
Worker
titleProperty
in interface Worker<V>
getTitle()
public final boolean cancel()
Worker
public boolean cancel(boolean mayInterruptIfRunning)
protected void updateProgress(long workDone, long max)
workDone
, totalWork
, and progress
properties. Calls to updateProgress are coalesced and run later on the FX application thread, and calls to updateProgress, even from the FX Application thread, may not necessarily result in immediate updates to these properties, and intermediate workDone values may be coalesced to save on event notifications. max
becomes the new value for totalWork
. This method is safe to be called from any thread.
workDone
- A value from -1 up to max. If the value is greater than max, an illegal argument exception is thrown. If the value passed is -1, then the resulting percent done will be -1 (thus, indeterminate).max
- A value from -1 to Long.MAX_VALUE. Any value outside this range results in an IllegalArgumentException.updateProgress(double, double)
protected void updateProgress(double workDone, double max)
workDone
, totalWork
, and progress
properties. Calls to updateProgress are coalesced and run later on the FX application thread, and calls to updateProgress, even from the FX Application thread, may not necessarily result in immediate updates to these properties, and intermediate workDone values may be coalesced to save on event notifications. max
becomes the new value for totalWork
. This method is safe to be called from any thread.
workDone
- A value from -1 up to max. If the value is greater than max, an illegal argument exception is thrown. If the value passed is -1, then the resulting percent done will be -1 (thus, indeterminate).max
- A value from -1 to Double.MAX_VALUE. Any value outside this range results in an IllegalArgumentException.protected void updateMessage(java.lang.String message)
message
property. Calls to updateMessage are coalesced and run later on the FX application thread, so calls to updateMessage, even from the FX Application thread, may not necessarily result in immediate updates to this property, and intermediate message values may be coalesced to save on event notifications. This method is safe to be called from any thread.
message
- the new messageprotected void updateTitle(java.lang.String title)
title
property. Calls to updateTitle are coalesced and run later on the FX application thread, so calls to updateTitle, even from the FX Application thread, may not necessarily result in immediate updates to this property, and intermediate title values may be coalesced to save on event notifications. This method is safe to be called from any thread.
title
- the new titlepublic final <T extends Event> void addEventHandler(EventType<T> eventType, EventHandler<? super T> eventHandler)
T
- the specific event class of the handlereventType
- the type of the events to receive by the handlereventHandler
- the handler to registerjava.lang.NullPointerException
- if the event type or handler is nullpublic final <T extends Event> void removeEventHandler(EventType<T> eventType, EventHandler<? super T> eventHandler)
T
- the specific event class of the handlereventType
- the event type from which to unregistereventHandler
- the handler to unregisterjava.lang.NullPointerException
- if the event type or handler is nullpublic final <T extends Event> void addEventFilter(EventType<T> eventType, EventHandler<? super T> eventFilter)
T
- the specific event class of the filtereventType
- the type of the events to receive by the filtereventFilter
- the filter to registerjava.lang.NullPointerException
- if the event type or filter is nullpublic final <T extends Event> void removeEventFilter(EventType<T> eventType, EventHandler<? super T> eventFilter)
T
- the specific event class of the filtereventType
- the event type from which to unregistereventFilter
- the filter to unregisterjava.lang.NullPointerException
- if the event type or filter is nullprotected final <T extends Event> void setEventHandler(EventType<T> eventType, EventHandler<? super T> eventHandler)
T
- the specific event class of the handlereventType
- the event type to associate with the given eventHandlereventHandler
- the handler to register, or null to unregisterjava.lang.NullPointerException
- if the event type is nullpublic final void fireEvent(Event event)
This method must be called on the FX user thread.
event
- the event to firepublic EventDispatchChain buildEventDispatchChain(EventDispatchChain tail)
EventTarget
EventTarget
. This event target is not automatically added to the chain, so if it wants to process events, it needs to add an EventDispatcher
for itself to the chain. In the case the event target is part of some hierarchy, the chain for it is usually built from event dispatchers collected from the root of the hierarchy to the event target.
The event dispatch chain is constructed by modifications to the provided initial event dispatch chain. The returned chain should have the initial chain at its end so the dispatchers should be prepended to the initial chain.
The caller shouldn't assume that the initial chain remains unchanged nor that the returned value will reference a different chain.
buildEventDispatchChain
in interface EventTarget
tail
- the initial chain to build fromCopyright (c) 2008, 2012, Oracle and/or its affiliates. All rights reserved. Use is subject to