gpt4 book ai didi

java - Java 中的多线程

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

我有一个循环,例如 for (int i=1;i<=10;i++)我想在其中创建 10 个线程,每个线程对一组数据执行相同的任务并返回结果。然后在循环内处理这个结果。有什么想法可以做到这一点吗?

for (int i=1;i<=10;i++) {
Work w = new Work();
Thread t = new Thread(w);
w.getResultFromThread();
//process w
}

class Work implements Runnable {
public void run() {
//perform tasks
}

public int getResultFromThread() {
return result;
}
}

我希望每个线程并行工作,但是当我收到结果时,它是一一的。

最佳答案

如果您不想使用执行器,您可以通过以下方式进行:

int size = 10;
Thread[] threads = new Thread[size];
Work[] works = new Work[size];
for (int i = 1; i <= size; i++) {

Work w = new Work();
works[i - 1] = w;
Thread t = new Thread(w);
threads[i - 1] = t;

// Start the thread
t.start();
}
// now you have started all the threads


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

// wait for each thread to complete execution, before extracting the result
// [here i am assuming that getResultFromThread() does not block
// till we get the result, if it blocks, then no need to join]
threads[i].join();

int result = works[i].getResultFromThread();
// do something with the result
}

关于java - Java 中的多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30582989/

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