javac
javac

Reputation: 61

How to create multiple threads using a loop in java

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);
    }
}

Upvotes: 5

Views: 8205

Answers (2)

xerx593
xerx593

Reputation: 13261

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());
    }
}

Upvotes: 2

Nir Alfasi
Nir Alfasi

Reputation: 53525

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

Upvotes: 9

Related Questions