[英]Sharing data between threads in Java
我無法從新線程訪問主線程中的數據。 我可以只使用主類的getter / setters就可以在沒有線程的情況下做到這一點。 但是,當我嘗試啟動新線程時,我將無法再這樣做。
主類:
public class Driver extends Application{
//create socket handlers
Runnable myNewThread = new workerThread();
//variables
private String lastMessage = "";
//getters and setters
public String setMyVariable() {
this.MyVariable = MyVariable;
}
//main
public static void main(String[] args) {
//launch threads
new Thread(myNewThread).start();
}
NewThread類:
public class workerThread implements Runnable{
public void run() {
Driver.setMyVariable("test");
}
我在workerThread
類中收到錯誤“無法解析符號'setMyVariable'”。 據我所知,這是因為我的workerThread線程不知道要引用哪個Driver實例(只有一個實例,但它不知道)。 有人可以幫助我了解我所缺少的嗎? 我已經看到了在主類的函數中聲明新類的示例,但是為了代碼組織的利益,我試圖避免這種情況,因為我的工作線程將變得有點大。
您正在調用setMyVariable("test")
,就好像它是靜態方法一樣。 您需要將Driver
類的實例傳遞給workerThread
實例。
public class workerThread implements Runnable {
private Driver driver;
public workerThread(Driver d, Class c) {
this.driver = d;
//do whatever you are doing with existing Classs parameter
}
public void run() {
driver.setMyVariable("test");
}
並更改Driver
類
public class Driver extends Application{
//create socket handlers
Runnable myNewThread = new workerThread(this, this.getClass());
//variables
private String lastMessage = "";
//getters and setters
public String setMyVariable() {
this.MyVariable = MyVariable;
}
//main
public static void main(String[] args) {
//launch threads
new Thread(new Driver().myNewThread).start();
}
}
更新:
並且由於myNewThread
變量也是非靜態的,因此必須在Driver.main()
執行以下Driver.main()
才能進行編譯:
new Thread(new Driver().myNewThread).start();
當您直接從類中調用函數時,系統會期望它是靜態的(就像您在這里執行的那樣: Driver.setMyVariable("test");
)但是您的函數不是靜態的,我認為它不應該像您一樣變量也不是靜態的。 如果您希望使用單獨的對象,則需要首先使用其構造函數實例化它們
您嘗試調用靜態方法而不將您的方法定義為靜態方法。 將您的方法更改為:
public static String setMyVariable() {
this.MyVariable = MyVariable;
}
然后,您還必須將MyVariable的定義更改為靜態。
不過,我不確定您是否了解自己所做的事情的后果。 創建靜態變量將使您可以在線程之間共享數據,因為在類的所有實例之間都將存在一個變量實例,但是如果您不真正了解靜態變量,則這樣做可能會很危險。
在做出此決定之前,請確保對此進行功課。
不要使其靜止。 傳遞您的對象的實例。
//Runnable myNewThread = new workerThread(this.getClass());
Runnable myNewThread = new workerThread(this);
然后,您的workerThread應該具有一個構造函數。
public class workerThread implements Runnable{
Driver driver;
public workerThread(Driver driver){
this.driver=driver;
}
public void run() {
driver.setMyVariable("test");
}
}
public class Driver extends Application{
public static Driver instance = new Driver();
//create socket handlers
public static Runnable myNewThread = new workerThread();
//variables
private String lastMessage = "";
private static String MyVariable = "";
//getters and setters
public static String setMyVariable(String MyVariable) {
instance.MyVariable = MyVariable;
return MyVariable;
}
//main
public static void main(String[] args) {
//launch threads
new Thread(myNewThread).start();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.