gpt4 book ai didi

java - 将线程积添加到数组

转载 作者:行者123 更新时间:2023-12-01 23:59:25 25 4
gpt4 key购买 nike

我必须将线程池的对象添加到ArrayList中,以便计算我的线程池创建的对象总数。为此,我创建了一个 ArrayList,在执行线程池后,我将该对象添加到 ArrayList。我的问题是,新的线程池会覆盖 Arraylist 中的现有对象,因此无论代码运行多少次,Arraylist 将始终保持相同的大小。

我的ArrayList:

 protected ArrayList<Runnable> ComponentBuild = new ArrayList<>();

线程启动的位置:

public void tireComponent() {
Menu menu = new Menu();
ExecutorService executor = Executors.newFixedThreadPool(3);
// ThreadPoolExecutor executor = new ThreadPoolExecutor();

for (int i = 1; i <= 3; i++) {
Runnable tire = new Tire("" + i);
executor.execute(tire);
ComponentBuild.add(tire);
System.out.println(ComponentBuild);
if (ComponentBuild.size() == MAX_CAPACITY) {
sleep();
}
}

轮胎类别:

public class Tire implements Runnable, Component {

private String number;

public Tire(String Number) {
this.number = Number;
}

@Override
public void run() {
System.out.println("Tire number " + number + " has now begun creation");

processCommand();

System.out.println("Thread " + Thread.currentThread().getName() + " has now created number " + number + " tire");
}

private void processCommand() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

@Override
public String toString() {
return this.number;
}
}

终端结果:

You have the following options: 
1) Create normal trie
2) Create winter tire
3) Create premium tire
1
[1]
Tire number 1 has now begun creation
[1, 2]
Tire number 2 has now begun creation
[1, 2, 3]

You have the following options:
1) Create normal trie
2) Create winter tire
3) Create premium tire
Tire number 3 has now begun creation
Thread pool-1-thread-2 has now created number 2 tire
Thread pool-1-thread-1 has now created number 1 tire
Thread pool-1-thread-3 has now created number 3 tire
1
[1]
Tire number 1 has now begun creation
[1, 2]
Tire number 2 has now begun creation
[1, 2, 3]
You have the following options:
1) Create normal trie
2) Create winter tire
3) Create premium tire
Tire number 3 has now begun creation
Thread pool-2-thread-1 has now created number 1 tire
Thread pool-2-thread-2 has now created number 2 tire
Thread pool-2-thread-3 has now created number 3 tire

我希望输出是这样的

Tire number 2 has now begun creation
[1, 2, 3, 4, 5, 6]

但实际输出是第二个线程池覆盖数组中的现有对象,因此无论我运行代码多少次,ArrayList 将始终是:

[1, 2, 3]

编辑:根据要求,我的组件接口(interface):

package Model;

public interface Component {

void run();
String toString();
}

最佳答案

您只运行循环三次“for (int i = 1; i <= 3; i++)”,因此它只有三次。如果您想要更多,则需要增加循环大小。

关于java - 将线程积添加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58186424/

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