gpt4 book ai didi

java - 整数值没有得到刷新

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:59:59 25 4
gpt4 key购买 nike

我正在尝试使用两个单独的线程打印偶数和奇数,这两个线程通过等待和通知相互通信。

我知道我指的是堆中的 Integer 对象。因此,一个线程所做的更改应该对两个线程都可见。我还使用 volatile 关键字来声明 Integet i。

我似乎无法理解变量 i 的值如何在递增后仍显示为 1。

代码的输出是

 Even Thread got lock i=1
Even Thread waiting.. i=1
Odd Thread got lock i=1
Odd Thread : i=2
Odd Thread Run called NotifyAll
Odd Thread got lock i=2
Odd Thread waiting.. i=2
Even Thread woken up.. i=1
Even Thread waiting.. i=1
package programs;


public class EvenOdd {
static Object lck = new Object();
volatile static Integer i=1;
volatile static Integer N = 1000;
public static void main(String args[]){
EvenRunner e = new EvenRunner(lck, i, N);
OddRunner o = new OddRunner(lck, i, N);
Thread t1 = new Thread(e,"Even Thread ");
Thread t2 = new Thread(o,"Odd Thread ");

t1.start();
t2.start();

try {
t1.join();
t2.join();
}catch(InterruptedException ex) {
System.out.println("Interrupted : "+ex);
}

}
}
class EvenRunner implements Runnable{
Object lck;
Integer i;
Integer N;
EvenRunner(Object lck,Integer i,Integer N){
this.lck=lck;
this.i=i;
this.N=N;
}
@Override
public void run() {


while(i<N) {

synchronized(lck) {
System.out.println(" Even Thread got lock i="+i);
while(i%2==1){
try {
System.out.println(" Even Thread waiting.. i="+i);
lck.wait();
System.out.println(" Even Thread woken up.. i="+i);
}catch(InterruptedException e) {
System.out.println("Interrupted thread : "+e);
}
}

++i;
System.out.println(Thread.currentThread().getName()+" : i="+i);

System.out.println(" Even Thread Run called NotifyAll");
lck.notifyAll();
}
}
}
}
class OddRunner implements Runnable{
Object lck;
Integer i;
Integer N;
OddRunner(Object lck,Integer i,Integer N){
this.lck=lck;
this.i=i;
this.N=N;
}
@Override
public void run() {
while(i<N) {
synchronized(lck) {
System.out.println(" Odd Thread got lock i="+i);
while(i%2==0){
try {
System.out.println(" Odd Thread waiting.. i="+i);
lck.wait();
System.out.println(" Odd Thread woken up.. i="+i);

}catch(InterruptedException e) {
System.out.println("Interrupted thread : "+e);
}
}

++i;
System.out.println(Thread.currentThread().getName()+" : i="+i);

System.out.println(" Odd Thread Run called NotifyAll");
lck.notifyAll();
}
}
}
}

预期结果:应该是其他线程在变量 I 递增后也应该看到它的值为 2。

实际结果:变量 i 的值在递增后仍被其他线程读取为 1。

最佳答案

Expected output should be that other thread should also see the value of variable I as 2 after it has been incremented.

当您构建 evenRunneroddRunner 时,您将相同的 Integer 引用作为实例字段复制到每个类中。

但是 Integer 是不可变的 - 当您执行 ++i; 时,它会更改字段以引用一个不同的 Integer 对象。它不会修改现有整数对象的内容...因此您的两个线程在完全独立的字段上运行,根本不会交互。

如果你想有一个单个对象,两个线程都可以修改,使用AtomicInteger相反。

关于java - 整数值没有得到刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56057912/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com