1 java multithreading static-variables thread-sleep java-threads
刚开始使用 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);
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
Thread-0 3
Thread-1 1
3
Run Code Online (Sandbox Code Playgroud)
为什么3即使第二个线程将静态变量的值更改为 1 也会打印?
是否会同时运行 3 个线程?
如果您在一个线程中更改变量,则它不会立即(或永远都不需要)对第二个线程可见,除非您使用某种同步原语,如Mutex. 您还可以使用原子类AtomicInteger来确保在一个线程中所做的更改对另一个线程可见。
文档中提供了更多信息。
| 归档时间: |
|
| 查看次数: |
129 次 |
| 最近记录: |