Reputation: 83
Can't get the correct value of count
in writer thread. It is always 1 in the writer thread even though it is changing in reader thread.
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);
}
}
}
Output:
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
Please let me know what is wrong with my code.
Upvotes: 1
Views: 92
Reputation: 72884
The code is not sharing the Integer
instance. count++
is equivalent to:
count = Integer.valueOf(count.intValue() + 1);
i.e. so you re-assign a new instance to the local variable count
. The instance itself is not changed (indeed Integer
is an immutable type).
In multithreaded scenarios, it might be better to use an AtomicInteger
.
Side note: you almost always should not invoke the Integer
constructor, always use Integer.valueOf(int)
.
Upvotes: 3