I'm trying to create multiple threads using a for loop in java so that they share the same variable counter. I'm doing something wrong because I want the counter to increment for each thread.
This is the output for the following code:
Counter: 1
Counter: 1
Counter: 1
public static void main(String[] args) {
int numThreads = 3;
for (int i = 0; i < numThreads; i++) {
Create c = new Create();
Thread thread = new Thread(c);
thread.start();
}
}
public class Create implements Runnable {
int counter = 0;
public void run() {
counter++;
System.out.println("Counter: " + counter);
}
}
Declare counter
as static and volatile:
static volatile int counter = 0;
and all 3 threads will share it.
Pay attention, though volatility take care of visibility (when one thread updates it - the change will be visible by the other threads) it does not take care of atomicity of the modification, for that you should either synchronize the part that you increment it, or better yet, use an AtomicInteger
My recommendation, (& picking up alfasin's edit), please consider this Create class implementation:
import java.util.concurrent.atomic.AtomicInteger;
public class Create implements Runnable {
static AtomicInteger classCounter = new AtomicInteger();
AtomicInteger objCounter = new AtomicInteger();
public void run() {
System.out.println("Class Counter: " + classCounter.incrementAndGet());
System.out.println("Object Counter: " + objCounter.incrementAndGet());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With