[英]Why do i have to synchronized an ArrayList of Threads?
So i need to create an ArrayList of Threads but according to 所以我需要创建一个线程的ArrayList但根据
Java - Filling an ArrayList of Threads with loop Java-用循环填充线程的ArrayList
it seems that i need to use the synchronized keyword, my question then is: 看来我需要使用synced关键字,然后我的问题是:
If im calling this only on the main thread why do i have to use the synchronized keyword? 如果即时消息仅在主线程上调用此函数,为什么我必须使用synced关键字? There are no others threads that could potentially do the same right?
没有其他线程可能会做同样的事情吗?
ArrayList<Thread> t = new ArrayList<Thread>();
for(int i=0;i<love.size();i++){
BTConnection cbtc = love.get(i).btc;
if(cbtc!=null){
Communicate temp = new Communicate(cbtc);
Thread ttemp = new Thread(temp);
ttemp.start();
t.add(ttemp);
}
}
Moreover if right below the code i use: 此外,如果在代码下面,我使用:
for(int i=0;i<t.size();i++){
t.get(i).join();
}
Does the for loop stop until the ith thread returns and then proceed to wait for the ith+1? for循环会在第ith个线程返回之前停止,然后继续等待ith + 1吗?
I don't see any reason why you would need to synchronize the threadlist, if only one thread is adding values into it/reading from it. 如果只有一个线程向其中添加值/从中读取值,我看不出您为什么需要同步线程列表的任何原因。 As for the second part, you are correct, the
join
-call will block until the i
'th thread has finished, before moving to wait for the next one. 至于第二部分,您是对的,
join
-call将阻塞直到第i
个线程完成,然后再等待下一个线程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.