我有一个静态变量,我想在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;但是当我在main函数中打印它时,它显示的是0。如何解决这个问题?
线程并发工作,所以你应该等到你的新线程完成:
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;
}
你必须了解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();
}
}
但在这里我建议采用与Philip相同的方法。只需在main函数中添加throws InterruptedException