Java 在多个线程之间共享对象
无法在写入线程中获取正确的Java 在多个线程之间共享对象,java,multithreading,thread-safety,semaphore,Java,Multithreading,Thread Safety,Semaphore,无法在写入线程中获取正确的计数值。它在写入线程中始终为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,即使它在读线程中正在更改
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
请让我知道我的代码有什么问题。代码没有共享整数
实例count++
相当于:
count=Integer.valueOf(count.intValue()+1)代码>
i、 e.因此您将一个新实例重新分配给局部变量count
。实例本身没有更改(实际上,Integer
是一个不可变的类型)
在多线程场景中,最好使用AtomicInteger
旁注:您几乎不应该总是调用Integer
构造函数,始终使用Integer.valueOf(int)
代码不共享Integer
实例count++
相当于:
count=Integer.valueOf(count.intValue()+1)代码>
i、 e.因此您将一个新实例重新分配给局部变量count
。实例本身没有更改(实际上,Integer
是一个不可变的类型)
在多线程场景中,最好使用AtomicInteger
旁注:您几乎不应该总是调用Integer
构造函数,而应该始终使用Integer。value of(int)
Integer
是不可变的。它不会被改变,取而代之的是一个具有不同价值的新的。谢谢@JohannesKuhn。我不知道说什么好。忘记了这样一个基本概念。Integer
是不可变的。它不会被改变,取而代之的是一个具有不同价值的新的。谢谢@JohannesKuhn。我不知道说什么好。忘记了这样一个基本的概念。其实,事实上