我有一個Java解決方案,其主線程運行JavaFX桌面應用程序。另外,還會創建另一個線程,通過使用嵌入式Web服務器來處理REST服務。通過使用REST客戶端,我可以訪問REST服務,但是我無法訪問主線程上下文中存在的對象,因爲我實際上並不在該線程中。請就如何解決這個問題提出任何建議。從Java中的另一個線程訪問/共享對象
public class Main extends Application {
public static MyBrowser myBrowser;
@Override
public void start(final Stage primaryStage) {
myBrowser = new MyBrowser("http://localhost:8080/terminal");
Scene scene1 = null;
Screen s1 = null;
Rectangle2D screenBounds = Screen.getScreens().get(0).getVisualBounds();
s1 = Screen.getScreens().get(0); // i replaced per 0
scene1 = new Scene(myBrowser, screenBounds.getWidth(), screenBounds.getHeight());
primaryStage.setTitle("Terminal 1");
primaryStage.setFullScreen(true);
primaryStage.setX(s1.getVisualBounds().getMinX());
primaryStage.setY(s1.getVisualBounds().getMinY());
primaryStage.setWidth(s1.getVisualBounds().getWidth());
primaryStage.setHeight(s1.getVisualBounds().getHeight());
primaryStage.setScene(scene1);
log.info("before show() method...");
primaryStage.show();
// launch jetty web-server for REST services
log.info("about to create a Thread object for running start() method...");
MyThread jettyThread = new MyThread();
jettyThread.setDaemon(true);
jettyThread.start();
}
public static MyBrowser getMyBrowser() {
return myBrowser;
}
public static void main(String[] args) {
launch(args);
}
public class MyBrowser extends Region {
HBox toolbar;
public WebView webView = new WebView();
WebEngine webEngine = webView.getEngine();
...
}
public class MyThread extends Thread {
public void run() {
try {
EmbeddedWebServerController.start();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
請提供示例代碼。此外,如果我正確理解你,_synchronized_關鍵字是要走的路 – user2358582
嗨user2358582,在這裏你會看到代碼。請詳細說明如何實現synchronized關鍵字。謝謝 – ekremer
我不知道如果它的完美方式去,但改變方法Main.getMyBrowser到「公共靜態同步MyBrowser getMyBrowser()」,並獲取對象如:Main.getMyBrowser()在方法mythread.run – user2358582