gpt4 book ai didi

java - 在多个线程之间共享对象

转载 作者:行者123 更新时间:2023-12-03 13:18:39 24 4
gpt4 key购买 nike

无法在编写器线程中获得count的正确值。即使它在阅读器线程中发生更改,在书写器线程中也始终为1。

public class ReaderWriter1 {

public static void main(String args[]) {

Semaphore rs = new Semaphore(1);
Integer count = new Integer(0);

Thread r1 = new Thread(new Reader("Reader 1", rs, count++));
Thread w1 = new Thread(new Writer("Writer 1", count));
w1.start();
r1.start();
}
}

class Reader implements Runnable {

String tName;
Semaphore rs;
Integer count;

Reader(String tName, Semaphore rs, Integer count) {
this.tName = tName;
this.rs = rs;
this.count = count;
}

@Override
public void run() {
try {
read();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

void read() throws InterruptedException {
while(true) {

rs.acquire();
count++;
rs.release();
System.out.println("Count in reader: " + count);
Thread.sleep(1000);
}
}

}

class Writer implements Runnable {

String tName;
Integer count;

Writer(String tName, Integer count) {
this.tName = tName;
this.count = count;
}

@Override
public void run() {

try {
write();
} catch (InterruptedException e1) {
e1.printStackTrace();
}

}

void write() throws InterruptedException {
while(true) {
System.out.println("Count in writer: " + count);
Thread.sleep(1000);
}
}

}

输出:
Count in writer: 1
Count in reader: 1
Count in writer: 1
Count in reader: 2
Count in reader: 3
Count in writer: 1
Count in writer: 1
Count in reader: 4
Count in writer: 1
Count in reader: 5
Count in writer: 1
Count in reader: 6
Count in writer: 1
Count in reader: 7
Count in reader: 8
Count in writer: 1
Count in reader: 9
Count in writer: 1

请让我知道我的代码有什么问题。

最佳答案

该代码未共享Integer实例。 count++等效于:
count = Integer.valueOf(count.intValue() + 1);
即,因此您将新实例重新分配给本地变量count。实例本身不会更改(实际上Integer是不可变的类型)。

在多线程方案中,最好使用AtomicInteger

旁注:,您几乎总是不应调用Integer构造函数,而应始终使用Integer.valueOf(int)

关于java - 在多个线程之间共享对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60906277/

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