繁体   English   中英

如何使用java中的循环创建多个线程

[英]How to create multiple threads using a loop in java

我正在尝试使用java中的for循环创建多个线程,以便它们共享相同的变量计数器。 我做错了,因为我希望计数器为每个线程递增。

这是以下代码的输出:

柜台:1
柜台:1
柜台: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);
    }
}

counter声明为静态 和易失性

static volatile int counter = 0;

并且所有3个线程都将共享它。

请注意,尽管波动性会考虑可见性(当一个线程更新它时 - 其他线程可以看到更改)它不会处理修改的原子性,因为您应该同步增加它的部分,或者更好的是,使用AtomicInteger

我的建议(&拿起alfasin的编辑),请考虑这个Create类实现:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM