刚开始使用Java中的线程,但我无法推断程序的输出
public class ThreadExample extends Thread{
private int info;
static int x = 0;
public ThreadExample (int info) {
this.info = info;
}
public void run () {
if ( info == 1 ) {
x = 3;
System.out.println(Thread.currentThread().getName() + " " + x);
} else{
x = 1;
System.out.println(Thread.currentThread().getName() + " " + x);
}
}
public static void main (String args []) {
ThreadExample aT1 = new ThreadExample(1);
ThreadExample aT2 = new ThreadExample(2);
aT1.start();
aT2.start();
System.err.println(x);
}
}
输出:Thread-0 3
Thread-1 1
3
为什么即使第二个线程将static变量的值更改为1,它也仍然打印3
?是否会同时运行3个线程?
最佳答案
如果您在一个线程中更改了变量,那么除非您使用某种同步原语(例如Mutex
),否则第二个线程将不会立即(或有必要)看到该变量。您还可以使用诸如AtomicInteger
之类的原子类来确保在一个线程中所做的更改对另一线程可见。
in the documentation有很多可用信息。
关于java - Java-线程和静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63271851/