package 对象及变量的并发访问2;
import java.util.ArrayList;
import java.util.List;
class MyLisetT2210{
private List list=new ArrayList();
synchronized public void add(String username){
System.out.println("ThreadName="+Thread.currentThread().getName()
+"执行了add方法!");
list.add(username);
System.out.println("ThreadName="+Thread.currentThread().getName()+
"退出了add方法!");
}
synchronized public int getSzie(){
System.out.println("ThreadName="+Thread.currentThread().getName()+
"执行了getsize方法()");
int szieValue=list.size();
System.out.println("ThreadName="+Thread.currentThread().getName()+
"退出了getsize方法()");
return szieValue;
}
}
class MyThreadAT2210 extends Thread{
private MyLisetT2210 lisetT2210;
public MyThreadAT2210(MyLisetT2210 myLisetT2210){
super();
this.lisetT2210=myLisetT2210;
}
@Override
public void run() {
for (int i=0;i<1000;i++){
lisetT2210.add("ThreadA"+(i+1));
}
}
}
class MyThreadBT2210 extends Thread{
private MyLisetT2210 myLisetT2210;
public MyThreadBT2210(MyLisetT2210 myLisetT2210){
super();
this.myLisetT2210=myLisetT2210;
}
@Override
public void run() {
for (int i=0;i<1000;i++){
myLisetT2210.add("threadB"+(i+1));
}
}
}
class TestT2210{
public TestT2210(){
MyLisetT2210 myLisetT2210=new MyLisetT2210();
MyThreadAT2210 at2210=new MyThreadAT2210(myLisetT2210);
at2210.setName("A");
at2210.start();
MyThreadBT2210 bt2210=new MyThreadBT2210(myLisetT2210);
bt2210.setName("B");
bt2210.start();
}
}
public class T2210 {
public static void main(String[] args) {
TestT2210 testT2210=new TestT2210();
}
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/51e22455dc6a7bbedc5a013fc027d89f.png)