验证方法调用是随机的——T2210

package 对象及变量的并发访问2;

import java.util.ArrayList;
import java.util.List;

/**
 * 验证方法调用是随机的
 *   同步代码块放在非同步synchronized方法进行生命,并不能保证调用方法的线程的执行同步(顺序性)
 * 也就是线程调用方法的顺序是无序的,虽然在同步块中执行的顺序是同步的。
 *
 *   从结果看 同步带啊方法中的代码是同步输出的,所以线程的进入与退出是成对的,但方法的调用是随机的,
 * 即线程A和B的执行时异步的。
 */

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();
    }
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值