use*_*457 1 java multithreading arraylist synchronized wait
我正在尝试运行 2 个并发线程,其中一个不断向列表添加对象,另一个更新这些对象,并可能从列表中删除其中一些对象。我有一个ArrayList用于我的方法和类的整个项目,所以现在很难改变它。
我环顾四周,发现了几种方法可以做到这一点,但正如我所说,很难从ArrayList. 我尝试使用synchronized和notify()将对象添加到列表wait()中的方法,以及更改这些对象的方法,如果它们满足某些条件,则可能会删除它们。
现在,我已经想出了如何使用 a 来做到这一点CopyOnWriteArrayList,但我想知道是否有可能使用ArrayList它自己来模拟这一点。这样我就不必编辑我的整个代码。
所以,基本上,我想做这样的事情,但是ArrayList:
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;
public class ListExample{
CopyOnWriteArrayList<MyObject> syncList;
public ListExample(){
syncList = new CopyOnWriteArrayList<MyObject>();
Thread thread1 = new Thread(){
public void run(){
synchronized (syncList){
for(int i = 0; i < 10; i++){
syncList.add(new MyObject(i));
}
}
}
};
Thread thread2 = new Thread(){
public void run(){
synchronized (syncList){
Iterator<MyObject> iterator = syncList.iterator();
while(iterator.hasNext()){
MyObject temp = iterator.next();
//this is just a sample list manipulation
if (temp.getID() > 3)
syncList.remove(temp);
System.out.println("Object ID: " + temp.getID() + " AND list size: " + syncList.size());
}
}
}
};
thread1.start();
thread2.start();
}
public static void main(String[] args){
new ListExample();
}
}
class MyObject{
private int ID;
public MyObject(int ID){
this.ID = ID;
}
public int getID(){
return ID;
}
public void setID(int ID){
this.ID = ID;
}
}
Run Code Online (Sandbox Code Playgroud)
我也读过,Collections.synchronizedList(new ArrayList())但我相信这需要我更改我的代码,因为我有大量的方法ArrayList作为参数。
任何指导将不胜感激,因为我没有想法。谢谢你。
您可能对java.util.concurrent软件包提供的集合感兴趣。它们对于生产者/消费者场景非常有用,在这种场景中,一个或多个线程将东西添加到队列中,而其他线程则将它们取走。根据您是要阻塞还是在队列已满/空时失败,有不同的方法。
关于重构您的方法,您应该使用接口(例如List)而不是具体的实现类(例如ArrayList)。这就是接口的目的,Java API 提供了很好的接口。
| 归档时间: |
|
| 查看次数: |
6012 次 |
| 最近记录: |