the code is as follows:
package com.obj;
import java.util.ArrayList;
import java.util.List;
public class MyList {
private List list = new ArrayList();
public void add(){
list.add("");
}
public int size(){
return list.size();
}
}
package com.thread;
import com.obj.MyList;
public class ThreadA extends Thread {
private MyList list;
public ThreadA(MyList list){
this.list=list;
}
@Override
public void run() {
try {
for (int i = 0; i <10 ; iPP) {
list.add();
System.out.println(""+(i+1)+"");
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package com.thread;
import com.obj.MyList;
public class ThreadB extends Thread {
private MyList list;
public ThreadB(MyList list){
this.list=list;
}
@Override
public void run() {
super.run();
try {
while (true){
if (list.size() == 5) {
System.out.println("==5,b");
throw new InterruptedException();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package com.demo;
import com.obj.MyList;
import com.thread.ThreadA;
import com.thread.ThreadB;
public class Run1 {
public static void main(String[] args) {
MyList service = new MyList();
ThreadA a = new ThreadA(service);
a.setName("A");
a.start();
ThreadB b = new ThreadB(service);
b.setName("B");
b.start();
}
}
listMyList.javalistvolatile
volatile,Biflist.size()
so it"s not clear what caused this