gpt4 book ai didi

Java多线程: why is execution not stopping at join()?

转载 作者:行者123 更新时间:2023-11-30 03:04:20 25 4
gpt4 key购买 nike

我有一个模块,可以在开始时从文件中反序列化一堆资源。每个都需要时间,所以我想以多线程方式实现它,以便每个线程摄取单个资源。根据我在网上找到的一些示例,我编写了这个测试类,它代表我的主模块的资源摄取步骤。

public class MultiThreadedResourceIngest {

private static ResourceClass1 r1 = null;
private static ResourceClass2 r2 = null;
private static ResourceClass3 r3 = null;

static class ResourceReader extends Thread {
private Thread t = null;
private int id = -1;
private String path2read = null;

ResourceReader( final int id, final String path2read){
this.id = id;
this.path2read = path2read;
}

public void run() {

if (path2read != null && path2read.length() > 0)
{
switch (id) {
case 0:
r1 = new ResourceClass1(path2read);
break;
case 1:
r2 = new ResourceClass2(path2read);
break;
case 2:
r3 = new ResourceClass3(path2read);
break;
default:
break;
}

}
log.info(String.format("Thread with id=%d and path=%s exiting", id, path2read));
}

public void start ()
{
if (t == null)
{
t = new Thread (this);
t.start ();
}
}

}

public static void main(String[] args) {

final String[] paths = new String[] {"path1", "path2", "path3"};

log.info("STARTING MTHREADED READ");
ArrayList<ResourceReader> rrs = new ArrayList<ResourceReader>();
for (int i=0; i < paths.length; i++)
{
ResourceReader rr = new ResourceReader(i,paths[i]);
rr.start();
rrs.add(rr);
}

log.info("JOINING");
for (ResourceReader rr: rrs)
{
try {
rr.join();
} catch (InterruptedException e) {
// Thread interrupted
e.printStackTrace();
}
}

// Want to reach this point only when all resources are ingested
//
log.info("MTHREADED FINISHED");
}

}

所以这里我有 3 个资源,我想在所有线程完成后到达标记为 //Want to get this point... 的点。这就是我实现 join() 循环的原因,只不过它没有按预期工作,即日志如下所示:

STARTING MTHREADED READ
Thread with id=0 and path=path1 exiting
JOINING
Thread with id=2 and path=path3 exiting
MTHREADED FINISHED
Thread with id=1 and path=path2 exiting

我需要更改什么才能等到所有资源都被读取后再继续?

最佳答案

您声明了 ResourceReader 扩展了 Thread,但您创建了另一个类并在 start 内启动它:

          t = new Thread (this);
t.start ();

您应该加入此线程,而不是

          rr.join();

因此,只需删除 ResourceReader 中的 start() 方法,一切都会正常工作。

关于Java多线程: why is execution not stopping at join()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35184738/

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