gpt4 book ai didi

Java 线程,错误的计数器

转载 作者:行者123 更新时间:2023-12-01 12:39:37 24 4
gpt4 key购买 nike

我运行下面的代码片段,并得到了意想不到的行为。也许它以正确的方式工作,但我需要让它以其他方式工作。详细信息如下。

import java.util.ArrayList;
import java.util.List;

public class TaskExample {

public static void main(String[] args) throws InterruptedException {
final PositionHolder holder = new PositionHolder();
final List<Integer> data = new ArrayList<Integer>();
List<Thread> threads = new ArrayList<Thread>();
for (int i = 0; i < 20; i++) {
holder.setPosition(i);
Thread t = new Thread() {

@Override
public void run() {
data.add(holder.getPosition());
}
};

t.start();
threads.add(t);
}

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

for(int i : data){
System.out.println(i);
}
}
}

class PositionHolder {

int position = 0;

public void setPosition(int position) {
this.position = position;
}

public int getPosition() {
return this.position;
}
}

我得到了结果:

10 12 9 8 6 6 5 4 2 1 16 16 18 19 19 19 19 19 19 19

为什么?我想要得到:

1 2 3 4 ...... 20

是否有任何选项可以改进此代码段?

最佳答案

试试这个代码;)

import java.util.ArrayList;
import java.util.List;

public class ogr
{

public static void main(String[] args) throws InterruptedException {
final PositionHolder holder = new PositionHolder();
final List<Integer> data = new ArrayList<Integer>();
for (int i = 0; i < 20; i++) {
holder.setPosition(i);
Thread t = new Thread() {

@Override
public void run() {
data.add(holder.getPosition());
}
};

t.start();
t.join();
}

for (int i : data) {
System.out.println(i);
}
}
}

class PositionHolder
{

int position = 0;

public void setPosition(int position) {
this.position = position;
}

public int getPosition() {
return this.position;
}
}

关于Java 线程,错误的计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25240016/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com