手動實現一個可重入鎖
阿新 • • 發佈:2018-01-04
必須 util 第一個 ret timeunit pac roo exc wait
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 publicvoid 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
...
手動實現一個可重入鎖