gpt4 book ai didi

java : accessing parent variable in multi threaded programe

转载 作者:太空宇宙 更新时间:2023-11-04 10:45:51 25 4
gpt4 key购买 nike

我有一个很大的 json 文件,其中包含很长的信息列表,并且我需要在许多子线程中只读该列表。
在java中,我们只能按值传递变量,而不是按引用传递变量,我希望我的程序在内存/磁盘使用方面尽可能轻
现在我将完整列表或仅其子列表传递给我创建的每个线程。
有没有办法从所有线程访问相同的 List 变量,而无需将完整的 List 复制到每个线程中?
我需要“仅阅读”列表

这是我的程序的工作原理

1 - 服务(等待文件创建)
2 - 将创建的Json文件内容读取到MyList
3 - 在具有不同限制/偏移的 MyList 部分上启动线程

我想做的是这样的事情

List<Map<String,String>> MyList = JsonToObject(filePath);
executor = Executors.newFixedThreadPool( 10 );

午餐者类(class)

List<Map<String,String>> MyList = JsonToObject(filePath);
executor = Executors.newFixedThreadPool( 10 );
int limit = 10;
int offset= 0;
for ( int i = 0 ; i < MyList.size() && offset < MyList.size() ; i++ ) {
offset = i * 10 ;
Child thread = new Child( limit , offset );
executor.submit( thread );
}

子类

public void run(){
for ( int i = this.offset ; i < this.limit ; i++ ) {
this.doSomthingWith ( Luncher.Mylist.get( i ) );
}
}

最佳答案

对列表的引用是按值传递的,因此只需将列表传递到您在线程中使用的任何方法即可。

关于java : accessing parent variable in multi threaded programe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48421721/

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