【发布时间】:2020-08-06 14:11:34
【问题描述】:
刚开始使用 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
为什么即使第二个线程将静态变量的值更改为 1,它也会打印 3?
会有3个线程同时运行吗?
【问题讨论】:
标签: java multithreading java-threads thread-sleep static-variables