Click here to Skip to main content
15,887,485 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Im trying to make 2 threads that read/write to a counter using thread safe methods.
Would I be better off using Atomic Integer to hold the value of the counter to allow me to safely increment it and get the value?

What I have tried:

Java
public class Counter {

    private int count;

    public Counter() {
        count = 0;
    }

    public synchronized void increment() {
        count++;
    }


    public synchronized int getVal() {
        return count;
    }
}


Java
public class Increment extends Thread {

    private static final int MAX = 1000;
    private Counter myCounter;

    public Increment(Counter c) {
        myCounter = c;
    }

    public void run() {
        for (int i = 0; i < MAX; i++) {
            myCounter.increment();
        }
    }
}


Java
public class Read extends Thread {

    private static final int MAX = 1000;
    private Counter myCounter;

    public Read(Counter c) {
        myCounter = c;
    }

    public void run() {
        for (int i = 0; i < MAX; i++) {
            System.out.println(myCounter.getVal());
        }
    }


Java
public static void main(String[] args) {

    Counter c = new Counter();

    Thread inc = new Increment(c);
    Thread read = new Read(c);

    inc.start();
    read.start();

}
Posted
Comments
Richard MacCutchan 27-Nov-17 12:35pm    
It rather depends on exactly what results you are trying to achieve.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900