各个线程依次间隔顺序打印消息
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class TongbuTest {
private class ThreadDemo implements Runnable{
private String sign;
private int delay;
private int order;
public ThreadDemo(String sign,int delay, int order) {
this.sign = sign;
this.delay = delay;
this.order = order;
}
@Override
public void run() {
for(int i=0;i<4;i++){
tongbu2(sign, order);
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public TongbuTest(){
lock = new ReentrantLock();
condition = lock.newCondition();
new Thread(new ThreadDemo("A", 2000, 0)).start();
new Thread(new ThreadDemo("B", 500, 1)).start();
new Thread(new ThreadDemo("C", 800, 2)).start();
}
public static final int THREAD_NUMBER = 3;
public int cnt = 0;
public Condition condition;
public ReentrantLock lock;
public void tongbu(String msg, int order){
lock.lock();
try {
while(cnt%THREAD_NUMBER != order){
condition.await();
}
cnt++;
System.out.println(msg);
condition.signalAll();
} catch (Exception e) {
e.printStackTrace();
} finally{
lock.unlock();
}
}
public synchronized void tongbu2(String msg, int order){
try {
while(cnt%THREAD_NUMBER != order){
wait();
}
cnt++;
System.out.println(msg);
notifyAll();
} catch (Exception e) {
}
}
public static void main(String [] args) {
new TongbuTest();
}
}