不同步导致的逻辑错误及其解决方法。——T2211

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

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

/**
 * 不同步导致的逻辑错误及其解决方法。
 *2——因为两个线程以异步的方式返回list参数的size大小
 * 1——将MyService中的操作改为同步
 *
 *   由于list参数对象在项目中是一份实例,是单例,而且也正需要对list参数的getsize方法做同步的调用,
 * 所以就对list参数进行同步处理。
 *
 */

class MyOneListT2211{
    private List liset=new ArrayList();

    synchronized public void add(String date){
        liset.add(date);
    };

    synchronized public int  getSize(){
        return liset.size();
    }
}

class MyServiceT2211{
    public MyOneListT2211 addServiceMethod(MyOneListT2211 listT2211,String date){
        try {
            synchronized (listT2211){
                if(listT2211.getSize()<1){
                    Thread.sleep(2000);
                    listT2211.add(date);
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return listT2211;
    }
}

class MyThread1T2211 extends Thread{
    private  MyOneListT2211 listT2211;

    public MyThread1T2211(MyOneListT2211 listT2211){
        super();
        this.listT2211=listT2211;
    }

    @Override
    public void run() {
        MyServiceT2211 myServiceT2211=new MyServiceT2211();
        myServiceT2211.addServiceMethod(listT2211,"A");

    }
}
class MyThread2T2211 extends Thread{
    private MyOneListT2211 myOneListT2211;

    public MyThread2T2211(MyOneListT2211 listT2211){
        super();
        this.myOneListT2211=listT2211;
    }

    @Override
    public void run() {
        MyServiceT2211 myServiceT2211=new MyServiceT2211();
        myServiceT2211.addServiceMethod(myOneListT2211,"B");
    }
}

class RunT2211{
    public RunT2211() throws InterruptedException {
        MyOneListT2211 myOneListT2211=new MyOneListT2211();

        MyThread1T2211 thread1T2211 =new MyThread1T2211(myOneListT2211);
        thread1T2211.setName("A");
        thread1T2211.start();

        MyThread2T2211 thread2T2111=new MyThread2T2211(myOneListT2211);
        thread2T2111.setName("B");
        thread2T2111.start();

        Thread.sleep(6000);

        System.out.println("listSize="+myOneListT2211.getSize());

    }
}
public class T2211 {
    public static void main(String[] args) throws InterruptedException {
        RunT2211 runT2211=new RunT2211();
    }
}

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值