【发布时间】:2014-04-02 05:20:47
【问题描述】:
请考虑以下代码:来源:http://docs.oracle.com/javafx/2/threads/jfxpub-threads.htm
import javafx.concurrent.Task;
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);
//Block the thread for a short time, but be sure
//to check the InterruptedException for cancellation
try {
Thread.sleep(100);
} catch (InterruptedException interrupted) {
if (isCancelled()) {
updateMessage("Cancelled");
break;
}
}
}
return iterations;
}
};
我正在学习 JavaFX,想知道是否必须创建 10 个独立线程。例如,Thread 1 将要从位于 IP 11.11.1.111 的 MySQL 中获取数据,Thread 2 将要从位于 IP 22.22.2.222 的 MySQL 中获取数据,所以我需要从以下位置开始编写代码@Override protected Integer call() throws Exception { 为 10 个线程中的每一个,这将是 10 次?
这是我现在拥有的:
public class MyClass extends Task<Integer>
{
private Class2 QRVC ;
// my variable declarations here
@Override protected Integer call() throws Exception {
// Defining logic to grab data from 11.11.1.111
// Updating the progress bar
}
@Override protected Integer call() throws Exception {
// Defining logic to grab data from 22.22.2.222
// Updating the progress bar
}
@Override protected Integer call() throws Exception {
// Defining logic to grab data from 33.33.3.333
// Updating the progress bar
}
}// END OF Class MyClass
【问题讨论】:
-
如何将作业分配给线程的逻辑完全取决于您。您可以编写 10 个不同的任务,或者您可以有一个类扩展任务并有一个逻辑来分离不同线程的功能!
-
我明白了。所以我可以有 10 个不同的
@Override protected Integer call() throws Exception {,这很好,对吧?我的意思是我有一个扩展Task<Integer>的课程,我打算写 10 种不同的`@Override protected Integer call() throws Exception { -
你不能有多个定义相同的方法,Java 不允许。你可以试试 !我建议您为 10 个不同的线程设置 10 个不同的任务!
-
@ItachiUchiha 我已经用我想要做的事情更新了我上面的代码。你是对的,Java 不允许我拥有具有相同定义的方法。你能否建议一个为 10 个不同线程拥有/定义多个任务的示例?谢谢
-
这段代码会给你重复的方法,编译时错误!
标签: java multithreading javafx