自定义个锁
import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock;
public class MyLock implements Lock { private boolean islock = false; Thread lockBy = null; int lockCount = 0; @Override public synchronized void lock() { Thread currentThread = Thread.currentThread(); while (islock && lockBy != currentThread){ try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } lockBy = Thread.currentThread(); islock = true; lockCount++; } @Override public synchronized void unlock() { if (lockBy == Thread.currentThread()){ lockCount--; if (lockCount == 0){ islock = false; notify(); } } } @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; } }
测试:线程安全
public class Sequence { private int value; MyLock lock = new MyLock(); public int getNext() { lock.lock(); value++; lock.unlock(); return value; } public static void main(String[] args) { Sequence sequence = new Sequence(); new Thread(() -> { while (true) { System.out.println(Thread.currentThread().getName() + " " + sequence.getNext()); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } ).start(); new Thread( () -> { while (true) { System.out.println(Thread.currentThread().getName() + " " + sequence.getNext()); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } ).start(); new Thread( () -> { while (true) { System.out.println(Thread.currentThread().getName() + " " + sequence.getNext()); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } ).start(); } }
运行结果:
结果显示:线程安全
测试:是否可重入
public class Demo { MyLock lock = new MyLock(); public synchronized void a() { lock.lock(); System.out.println("a"); b(); lock.unlock(); } public synchronized void b() { lock.lock(); System.out.println("b"); lock.unlock(); } public static void main(String[] args) { Demo d = new Demo(); new Thread(()-> { d.a(); }).start(); } }
运行结果:
结果证明: a方法和b方法都可以进入了,是可重入锁。
完