标签:print cep port -- unlock package 轮询 thread equals
package com.xp.test;import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ABC_Lock {
public static void main(String[] args) {
Print print = new Print();
// new Thread(new Runnable() {
// @Override
// public void run() {
// for (int i = 1; i <= 34; i++) {
// print.loopA(i);
// }
// }
// }, "A").start();
// new Thread(new Runnable() {
// @Override
// public void run() {
// for (int i = 1; i <= 33; i++) {
// print.loopB(i);
// }
// }
// }, "B").start();
// new Thread(new Runnable() {
// @Override
// public void run() {
// for (int i = 1; i <= 33; i++) {
// print.loopC(i);
// }
// }
// }, "C").start();
// }
int i = 33;
while (i > 0) {
i--;
new Thread(new Runnable() {
@Override
public void run() {
print.loopA();
}
}, "A").start();
new Thread(new Runnable() {
@Override
public void run() {
print.loopB();
}
}, "B").start();
new Thread(new Runnable() {
@Override
public void run() {
print.loopC();
}
}, "C").start();
}
}
}
class Print {
private Lock lock = new ReentrantLock();
private Condition conditionA = lock.newCondition();
private Condition conditionB = lock.newCondition();
private Condition conditionC = lock.newCondition();
int tick = 100;
String mark = "a";
public void loopA() {
lock.lock();
try {
if (!"a".equals(mark)) {
try {
conditionA.await();
} catch (InterruptedException e) {
}
}
System.out.println(Thread.currentThread().getName() + "完成售票,剩余: " + --tick);
mark = "b";
conditionB.signal();
} finally {
lock.unlock();
}
}
public void loopB() {
lock.lock();
try {
if (!"b".equals(mark)) {
try {
conditionB.await();
} catch (InterruptedException e) {
}
}
System.out.println(Thread.currentThread().getName() + "完成售票,剩余: " + --tick);
mark = "c";
conditionC.signal();
} finally {
lock.unlock();
}
}
public void loopC() {
lock.lock();
try {
if (!"c".equals(mark)) {
try {
conditionC.await();
} catch (InterruptedException e) {
}
}
System.out.println(Thread.currentThread().getName() + "完成售票,剩余: " + --tick);
mark = "a";
conditionA.signal();
} finally {
lock.unlock();
}
}
}
标签:print cep port -- unlock package 轮询 thread equals
原文地址:http://blog.51cto.com/13306517/2131219