简体   繁体   中英

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

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

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