码迷,mamicode.com
首页 > 其他好文 > 详细

手动实现一个可重入锁

时间:2018-01-04 14:23:01      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:run   可重入   color   als   boolean   bool   imp   必须   bsp   

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
...

 

手动实现一个可重入锁

标签:run   可重入   color   als   boolean   bool   imp   必须   bsp   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!