使用线程发出数据库请求我试图了解线程在java中是如何工作的。这是一个返回ResultSet的简单数据库请求。我在使用JavaFX。 package application;import java.sql.ResultSet;import java.sql.SQLException;import javafx.fxml.FXML;import javafx.scene.control.Button;
import javafx.scene.control.Label;import javafx.scene.control.TextField;public class Controller{
@FXML
private Button getCourseBtn;
@FXML
private TextField courseId;
@FXML
private Label courseCodeLbl;
private ModelController mController;
private void requestCourseName(){
String courseName = "";
Course c = new Course();
c.setCCode(Integer.valueOf(courseId.getText()));
mController = new ModelController(c);
try {
ResultSet rs = mController.<Course>get();
if(rs.next()){
courseCodeLbl.setText(rs.getString(1));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}// return courseName;
}
public void getCourseNameOnClick(){
try {// courseCodeLbl.setText(requestCourseName());
Thread t = new Thread(new Runnable(){
public void run(){
requestCourseName();
}
}, "Thread A");
t.start();
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}这将返回一个异常:线程“Thread A”中的异常java.lang.IllegalStateException:不在FX应用程序线程上;currentThread=Thread A如何正确地实现线程处理,以便在第二个线程而不是主线程中执行每个数据库请求?我听说过实现Runnable,但是如何在Run方法中调用不同的方法呢?以前从来没有用过线程,但我想是时候开始了。
3 回答
慕尼黑的夜晚无繁华
TA贡献1864条经验 获得超6个赞
线程“Thread A”中的异常java.lang.IllegalStateException:不在FX应用程序线程上;currentThread=Thread A
courseCodeLbl.setText(rs.getString(1)); // <--- The culprit
如果我不能这样做,我如何使用背景线程?
用Platform.runLater包装场景图元素
Plaform.runLater
Platform.runLater(() -> courseCodeLbl.setText(rs.getString(1)));
使用任务
updateMessage
courseCodeLbl
Task<Void> task = new Task<Void>() { @Override public Void call() { String courseName = ""; Course c = new Course(); c.setCCode(Integer.valueOf(courseId.getText())); mController = new ModelController(c); try { ResultSet rs = mController.<Course>get(); if(rs.next()) { // update message property updateMessage(rs.getString(1)); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }}public void getCourseNameOnClick(){ try { Thread t = new Thread(task); // To update the label courseCodeLbl.textProperty.bind(task.messageProperty()); t.setDaemon(true); // Imp! missing in your code t.start(); } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); }}
HUH函数
TA贡献1836条经验 获得超4个赞
public void getCourseNameOnClick(){ new Thread(new Runnable(){ public void run(){ String courseName = requestCourseName(); Platform.runLater(new Runnable(){ courseCodeLbl.setText(courseName) }); } }, "Thread A").start();}
添加回答
举报
0/150
提交
取消