Synchronized和ReentrantLock包装线程不安全的类_demo

package com.thread.concurrent;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class CirticalSection
{
    // Test the two different approaches :

    static void testApproaches(PairManager pman1, PairManager pman2)
    {
        ExecutorService exec = Executors.newCachedThreadPool();

        PairManipulartor pm1 = new PairManipulartor(pman1), pm2 = new PairManipulartor(pman2);

        PairChecker pcheck1 = new PairChecker(pman1), pcheck2 = new PairChecker(pman2);

        exec.execute(pm1);
        exec.execute(pm2);
        exec.execute(pcheck1);
        exec.execute(pcheck2);

        try
        {
            TimeUnit.MILLISECONDS.sleep(500);
        }
        catch (InterruptedException e)
        {
            System.out.println("sleep interrupted");
        }

        System.out.println("pm1 : " + pm1 + "\n pm2 :" + pm2);
        System.exit(0);

    }

    public static void main(String[] args)
    {
        PairManager pman1 = new PairManager1(), pman2 = new PairManager2();

        testApproaches(pman1, pman2);
    }

}

class Pair
{
    // Not thread-safe
    private int x;

    private int y;

    public Pair(int x, int y)
    {
        this.x = x;
        this.y = y;
    }

    public Pair()
    {
        this(0, 0);
    }

    public int getX()
    {
        return x;
    }

    public void incrementX()
    {
        x++;
    }

    public int getY()
    {
        return y;
    }

    public void incrementY()
    {
        y++;
    }

    @Override
    public String toString()
    {
        return "pair [x=" + x + ", y=" + y + "]";
    }

    public class PairValuesNotEqualException extends RuntimeException
    {
        public PairValuesNotEqualException()
        {
            super("Pair values not equal : " + Pair.this);
        }
    }

    // Arbitrary invariant -- both variables must be equal:
    public void checkState()
    {
        if (x != y)
            throw new PairValuesNotEqualException();
    }

}

// Protect a pair inside a thread-safe class:
abstract class PairManager
{
    AtomicInteger checkCounter = new AtomicInteger(0);

    protected Pair p = new Pair();

    private List<Pair> storage = Collections.synchronizedList(new ArrayList<Pair>());

    public synchronized Pair getPair()
    {
        // Make a copy to keep the original safe
        return new Pair(p.getX(), p.getY());
    }

    // Assume this is a time consuming operation
    protected void store(Pair p)
    {
        storage.add(p);
        try
        {
            TimeUnit.MILLISECONDS.sleep(50);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
    }

    public abstract void increment();

}

// Synchronize the entire method :
class PairManager1 extends PairManager
{
    @Override
    public synchronized void increment()
    {
        p.incrementX();
        p.incrementY();
    }
}

// Use a critical section
class PairManager2 extends PairManager
{
    Pair temp;

    @Override
    public void increment()
    {
        p.incrementX();
        p.incrementY();
        temp = p;
    }
}

class PairManipulartor implements Runnable
{
    private PairManager pm;

    public PairManipulartor(PairManager pm)
    {
        this.pm = pm;
    }

    @Override
    public void run()
    {
        while (true)
            pm.increment();
    }

    @Override
    public String toString()
    {
        return "Pair : " + pm.getPair() + " checkCounter = " + pm.checkCounter.get();
    }
}

class PairChecker implements Runnable
{
    private PairManager pm;

    public PairChecker(PairManager pm)
    {
        this.pm = pm;
    }

    @Override
    public void run()
    {
        while (true)
        {
            pm.checkCounter.incrementAndGet();
            pm.getPair().checkState();
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值