【问题标题】:Thread safety if loop is thread safe [duplicate]如果循环是线程安全的,则线程安全[重复]
【发布时间】:2021-06-09 06:18:17
【问题描述】:

这个问题中的while循环是线程安全的:AtomicInteger thread safety。如果我在线程安全的while循环中插入randomSum方法,代码仍然是线程安全的吗?还是应该同步 randomSum 方法?

import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

public class Print implements Runnable {
    static AtomicInteger atomicInteger = new AtomicInteger(0);
    static Random random = new Random(1);

    public static int randomSum() {
        int sum = 0;
        for (int i = 0; i < 10; i++) {
            sum += random.nextInt();
        }
        return sum;
    }

    @Override
    public void run() {
        while (atomicInteger.getAndIncrement() < 100)
            System.out.println(randomSum() + " " + Thread.currentThread());
    }

    public static void main(String[] args) throws InterruptedException {
        ArrayList<Thread> threads = new ArrayList<>();

        for (int i = 0; i < 5; i++)
            threads.add(new Thread(new Print()));

        for (Thread thread : threads)
            thread.start();

        for (Thread thread : threads)
            thread.join();
    }
}

【问题讨论】:

  • 是的,仍然是线程安全的。无需同步此randomSum 方法,因为您没有修改该方法之外的任何值。
  • @Sachith Dickwella 好吧 - 实际上 random.nextInt 在内部修改了 random,但 Random 是线程安全的。
  • 这不完全是stackoverflow.com/questions/5819638 的副本,但如果Random 是线程安全的,那么您的randomSum 方法是线程安全的,因为sum 和@987654329 @ 是局部变量,因此是线程受限的。

标签: java thread-safety atomicinteger


【解决方案1】:

randomSum 方法是线程安全的,就像它的使用一样。

唯一的共享对象是random。 Java API 文档指出 java.util.Random 的实例是线程安全的,但如果同时使用(可能是由于同步)可能会遇到性能问题,如果性能有问题,则应考虑使用 ThreadLocalRandom

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-22
    • 1970-01-01
    • 2010-12-10
    相关资源
    最近更新 更多