java - 线程输出错误

标签 java multithreading

我想打印出每个线程的编号,即1,2,3..。无论输出数字的顺序如何,但是当我运行下面的代码时,输​​出中重复了许多数字

public static int ThreadNumber = 0;

for (int i = 0; i <= 8; i++) {

        new Thread(() -> {
            System.out.println("Thread number : " +  ThreadNumber);
        }).start();

        ThreadNumber++;
}

输出:

Thread number : 3
Thread number : 3
Thread number : 4
Thread number : 5
Thread number : 6
Thread number : 9
Thread number : 9
Thread number : 9
Thread number : 9

如何解决此问题,以便每个线程仅输出特定数字

最佳答案

避免可变的全局状态(“静态”)。

要将值传递给 lambda 表达式,请将其分配给有效的最终局部变量。目前还不需要升级到整个类(class)。

int threadNumber = 0;

for (int i = 0; i <= 8; i++) {
    int thisThread = threadNumber;
    new Thread(() -> {
        System.out.println("Thread number : " +  thisThread);
    }).start();

    ++threadNumber; // Just i in this case.
}

显然,无法保证打印的顺序 - 这就是线程的要点。

关于java - 线程输出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59688210/

相关文章:

java - 线程 "main"java.lang.ArrayIndexOutOfBoundsException : 0 中的异常

java: 是否可以为按钮数组设置 lambda 表达式作为 for 循环?如果是这样怎么办?

java - 无法找到 MyModule.gwt.xml 使用 Ant 编译 GWT 项目

java - 线程失去锁并给另一个线程执行的机会

multithreading - 在 Rust 中,如何创建在其自己的操作系统线程中运行的任务?

c# - 关于缓存的线程安全 IEnumerable<T> 实现的性能

java - 在共享包中使用 GWT 的 NumberFormat 类

java - 如何从 TestNG 数据提供程序跳过数据集(出错时)?

.NET 单元测试框架,可以处理多个线程的测试

C volatile 内存模型