首页 > 其他 > 详细

手动实现一个可重入锁

时间:2018-01-04 14:00:24      阅读:246      评论:0      收藏:0      [点我收藏+]
package com.roocon.thread.ta1;

public class Sequence {

    private MyLock lock = new MyLock();

    private int value;

    public int getNext() {
        lock.lock();
        value++;
        lock.unlock();
        return value;

    }

    public static void main(String[] args) {

        Sequence s = new Sequence();

        new Thread(new Runnable() {

            @Override
            public void run() {
                while(true)
                    System.out.println(s.getNext());
            }
        }).start();
        new Thread(new Runnable() {

            @Override
            public void run() {
                while(true)
                    System.out.println(s.getNext());
            }
        }).start();
        new Thread(new Runnable() {

            @Override
            public void run() {
                while(true)
                    System.out.println(s.getNext());
            }
        }).start();
        new Thread(new Runnable() {

            @Override
            public void run() {
                while(true)
                    System.out.println(s.getNext());
            }
        }).start();
        new Thread(new Runnable() {

            @Override
            public void run() {
                while(true)
                    System.out.println(s.getNext());
            }
        }).start();
    }

}

 

package com.roocon.thread.ta1;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

public class MyLock implements Lock {

private boolean isLocked = false;

@Override
public synchronized void lock() {
/*
if (isLocked == false) {//第一个进来的线程不需要等待
isLocked = true;
}else {//其他线程需要等待
try {
wait();//使用wait模拟等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
*/
if (isLocked) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
isLocked = true;

}

@Override
public synchronized void unlock() {
isLocked = false;
notify();//wait notify 必须和synchronized一起使用
}


@Override
public void lockInterruptibly() throws InterruptedException {

}

@Override
public boolean tryLock() {
return false;
}

@Override
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
return false;
}

@Override
public Condition newCondition() {
return null;
}
}

 

运行结果:

1
2
3
4
5
6
7
...

 

手动实现一个可重入锁

原文:https://www.cnblogs.com/sunnyDream/p/8192699.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!