我有一个静态变量,我想在run()方法中设置。我有以下内容:
public class Test{
public static int temp;
public static void main(String [] args)
{
update();
System.out.println("This is the content of temp"+temp);
}
public static void update()
{
(new Thread() {
@Override
public void run() {
// do some stuff
Test.temp=15;
}}).start();
}
我想将temp的内容更新为15;但是当我在主函数中打印它时,它显示0.如何修复它?
答案 0 :(得分:3)
线程并发工作,所以你应该等到新线程结束:
public class Test{
public static int temp;
public static void main(String [] args) {
update().join(); //we wait until new thread finishes
System.out.println("This is the content of temp"+temp);
}
public static Thread update() {
Thread t = new Thread() {
@Override
public void run() {
// do some stuff
Test.temp=15;
}
};
t.start();
return t;
}
答案 1 :(得分:1)
您必须了解Thread的工作原理。
我将首先向您展示两段代码,首先要理解,在线程内初始化的变量需要花费时间来更新,直到线程完成。
public class Num {
public static int temp;
public static void main(String [] args) throws InterruptedException
{
update();
System.out.println("This is the content of temp"+Num.temp);//This will print before temp=15 is updated
}
public static void update()
{
(new Thread() {
@Override
public void run() {
// do some stuff
Num.temp=15;
System.out.println("Value of temp:"+Num.temp);//This statement prints after
}}).start();
}
}
打印以下内容:
This is the content of temp0
Value of temp:15
第二个显示,如果在执行线程后等待一小段时间(Thread.sleep(10)),则值会更新:
public class Num {
public static int temp;
public static void main(String [] args) throws InterruptedException
{
update();
Thread.sleep(10);
System.out.println("This is the content of temp"+Num.temp);//This will print correct value now
}
public static void update()
{
(new Thread() {
@Override
public void run() {
// do some stuff
Num.temp=15;
}}).start();
}
}
但在这里,我建议采用与菲利普相同的方法。只需在主要功能
中添加throws InterruptedException
即可