简体   繁体   中英

Sharing object between multiple threads

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.

The code is not sharing the Integer instance. count++ is equivalent to:

count = Integer.valueOf(count.intValue() + 1);

ie 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) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM