Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create multiple threads using a loop in java

Tags:

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);
    }
}
like image 901
javac Avatar asked Apr 26 '15 23:04

javac


2 Answers

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

like image 106
Nir Alfasi Avatar answered Oct 04 '22 00:10

Nir Alfasi


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());
    }
}
like image 44
xerx593 Avatar answered Oct 04 '22 02:10

xerx593