考虑以下代码:
static class ThreadTest extends Thread {
int x;
int[] y;
public ThreadTest(int x, int[] y) {
this.x = x;
this.y = y;
}
@Override
public void run() {
while (x< 10) {
++x;
System.out.print("0");
}
while (y[0] < 10) {
++y[0];
System.out.print('1');
}
}
}
public static void main(String args[]) {
int x = 0;
int[] y = new int[1];
y[0] = 0;
Thread A = new ThreadTest(x, y);
Thread B = new ThreadTest(x, y);
B.start();
A.start();
}
将打印多少个 1 和多少个 0? 如何保证程序每次运行时1的个数相同? 请注意,该类是静态
如何评估“1”的最大和最小出现次数?
最佳答案
目前,您的代码包含 race condition因为两个线程正在修改相同的 y 数组。这意味着打印的 1 数量是不确定的。
how can I ensure that the number of 1's will be the same every time the program runs?
您需要在两个线程之间引入同步。
这可以通过多种方式完成。 Java 中最常见的一种是在修改和/或读取共享状态的代码周围使用synchronized
block 。
另一种方法是将 int[1]
数组替换为单个 AtomicInteger
。对于这种特殊情况,这非常有效。
notice that the class is static
类是否是静态
在这里完全不相关。 All it means问题是 ThreadTest 的实例没有对外部类的实例的隐式引用。它与 ThreadTest 实例之间的状态共享无关(我认为这就是您在这里所暗示的意思)。
关于java线程对静态类的影响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10664346/