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