So i need to create an ArrayList of Threads but according to
Java - Filling an ArrayList of Threads with loop
it seems that i need to use the synchronized keyword, my question then is:
If im calling this only on the main thread why do i have to use the synchronized keyword? 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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.