使用synchronized关键字封装一个锁

九路 发表时间: 2020-09-09 09:44 阅读:53 收藏:0

代码如下:

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

打印的结果如下:
17623795688d0ed0d5b6ea0.png

收藏
评论区
发表评论