我尝试实现等待/通知机制来修改ArrayList
使用两个单独的线程。
第一次迭代似乎工作正常,但第二次迭代它在addToArray()
方法中永远等待。我无法弄清楚为什么它在方法中永远等待?根据我的理解,当其他线程等待时,其他线程(删除项目)应该接起。
请查看并指出可能的错误(如果有)。我知道我可以用来Vector
进行线程安全操作,但这不是我想要的。
package threadTest;
import java.util.*;
public class DhagaJava {
public static void main(String...strings){
ArrayModification am = new ArrayModification();
Thread t1 = new Thread(new AddToArray(am));
Thread t2 = new Thread(new RemoveFromArray(am));
t1.start();
t2.start();
}
}
class ArrayModification{
boolean added = false;
ArrayList<Integer> al;
ArrayModification(){
al = new ArrayList<Integer>();
}
public synchronized void addToArrayList(int x) {
if (added == true){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.al.add(x);
System.out.println(al);
System.out.println("Added!! :)");
added = true;
notifyAll();
}
public synchronized void removeFromList(){
if( added== false){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(al);
this.al.remove(0);
System.out.println("Removed!! :' ");
added = false;
notifyAll();
}
}
class AddToArray implements Runnable{
ArrayModification ma;
AddToArray(ArrayModification m){
this.ma = m;
}
public void run() {
for (int i = 0; i<10; i++)
ma.addToArrayList(i);
}
}
class RemoveFromArray implements Runnable{
ArrayModification ma;
RemoveFromArray(ArrayModification a){
this.ma = a;
}
public void run(){
ma.removeFromList();
}
}
class RemoveFromArray implements Runnable{
ArrayModification ma;
RemoveFromArray(ArrayModification a){
this.ma = a;
}
public void run(){
//for(int j=11;j<20; j++)
ma.removeFromList();
}
}
输出是:
[0]
Added!! :)
[0]
Removed!! :'
[1]
Added!! :)