使用synchronized关键字封装一个锁

代码如下:

public class Lock {
    private boolean isLocked = false;

    public void lock() {
        synchronized (this) {
            while (isLocked) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    isLocked = false;
                    break;
                }
            }
            isLocked = true;
        }
    }

    public void unLock() {//也可以把synchronized放在方法前
        synchronized (this) {
            isLocked = false;
            notifyAll();
        }
    }
}

用法如下:

public class Counter {
    private int count = 0;

    private Lock mLock = new Lock();

    public void inc(){
        mLock.lock();
        count++;
        mLock.unLock();
    }

    public int getCount(){
        return count;
    }

    public static void main(String[] args) throws InterruptedException {

        Counter counter = new Counter();

        for (int i = 0; i < 500; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {

                    try {
                        Thread.currentThread().sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    counter.inc();
                }
            }).start();
        }


        Thread.currentThread().sleep(1000 * 5);
        System.out.println("count=" + counter.getCount());
    }
}

打印的结果如下:


使用synchronized关键字封装一个锁_第1张图片
image.png

你可能感兴趣的:(使用synchronized关键字封装一个锁)