无法使用可运行线程从另一个类更改变量

问题描述 投票:0回答:1

我正在尝试创建一个程序,需要在按钮上更改轮廓,但是当我尝试在run()方法中更改图形时,无法获得轮廓。因为有太多与该问题无关的代码,所以我试图缩短所有代码,并且存在相同的问题-变量不变。

类/控制器(如果在jfx中)

public class NewClass {
    static int x = 12;
    Thread thread;
    public void Example(){
        thread = new Thread(new Thread1());
    }
}

线程

public class Thread1 implements Runnable{
    @Override
    public void run(){
        NewClass.x = 1;
    }

}

主要(我试图获取它来确保它会等待线程完成)

public class JavaApplication5 {
        public static void main(String[] args) {
            NewClass theClass = new NewClass();
            theClass.Example();
            try{
                while(theClass.thread.isAlive()){
                    System.out.println("Not in use");
                }
            }catch(Exception e){
                System.out.println(theClass.x);
            }
            System.out.println(theClass.x);
       }    
}

即使应该更改输出,输出始终为12?

我不确定为什么变量没有改变

java multithreading runnable
1个回答
0
投票

您正在创建一个新线程,但是您没有在任何地方运行它

thread.start()添加到您的示例方法中以运行它

© www.soinside.com 2019 - 2024. All rights reserved.