![](/img/trans.png)
[英]If a method belongs to another class that extends Thread but is called from the main thread, will it be executed by main or a child thread? (Java)
[英]Java method called from another thread, data update is not instantaneous
我正在嘗試使用一個單獨的線程來遍歷Java中的嵌套循環(以避免凍結UI,並使事情變得更簡單):
public class scan2D extends Thread{
public void run(){
float data;
for (int y = 0; y<GUI.max_y; y++) {
for (int x = 0; x<GUI.max_x; x++) {
GUI.model.set(GUI.edaq.getdata());
}
}
GUI.model.save();
}
}
在GUI對象中創建scan2d對象,並通過按GUI的啟動按鈕將其啟動。 一切正常,除了“模型”對象僅更新一次,最后更新所有數據,而不是一次更新一次。 我想從“ edaq”讀取數據並將其發送到模型后立即對其進行更新。 通過視圖觀察模型。 如何使更新立即生效?
更新感謝您的所有幫助建議和評論! 抱歉,我沒有提供所有顯然引起問題的代碼。 我是初學者。 我做了一個簡化的,最小的“工作”示例,該示例也顯示了症狀:
package test;
public class GUI {
static Model model;
static scan2D scan2d;
public GUI() {
model = new Model();
scan2d = new scan2D();
scan2d.start();
}
public static void main(String[] args) {
new GUI();
}
}
class Model {
public void set(int data)
{
System.out.print(data);
}
}
public class scan2D extends Thread {
public void run(){
int data;
for (int y = 0; y<=10; y++) {
for (int x = 0; x<=10; x++) {
try {Thread.sleep(100);}
catch(InterruptedException ex){}
GUI.model.set(x+y);
}
}
}
}
當我嘗試延遲100毫秒時,同時在netbeans輸出窗口中顯示了最后顯示的所有數據。 當我使用1000s時,它可以工作,數據會在輸出上一一顯示。 這只是顯示問題嗎?
在您的情況下,每次數據更改時都應啟動新線程(也稱為執行run
方法)。 我只能猜測,在對模型進行所有更改之后,您只能啟動一次新線程。 我對嗎?
您的GUI如何觀察模型的變化? 我認為您必須通知該家伙以執行更新。 此通知必須在事件分發線程上執行。
所有影響gui的東西都必須在gui的線程上發生-例如通過
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
// update guy
}
});
我認為問題可能是您的模型僅在GUI.model.save();
發送通知GUI.model.save();
。 所以你應該調用GUI.model.save()
; 每次更改模型后:
public class scan2D extends Thread{
public void run(){
float data;
for (int y = 0; y<GUI.max_y; y++) {
for (int x = 0; x<GUI.max_x; x++) {
GUI.model.set(GUI.edaq.getdata());
GUI.model.save();
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.