在java中的run()方法中设置静态变量
我想在run()方法中设置一个静态变量。我有以下资料:在java中的run()方法中设置静态变量,java,multithreading,thread-safety,concurrent-programming,Java,Multithreading,Thread Safety,Concurrent Programming,我想在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()
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();
}
This is the content of temp0
Value of temp:15
我想临时的内容更新到15;但是当我在主函数中打印它时,它显示为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;
}
你必须了解线程是如何工作的 我将在这里向您展示两段代码首先要理解的是,在线程内初始化的变量需要时间更新,直到线程完成
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();
}
}
它打印以下内容:
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();
}
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();
}
}
但在这里,我建议采用与菲利普相同的方法。只需在main函数中添加抛出InterruptedException