多线程通讯轮询卖票了解一下
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多线程通讯轮询卖票了解一下相关的知识,希望对你有一定的参考价值。
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();
}
}
}
以上是关于多线程通讯轮询卖票了解一下的主要内容,如果未能解决你的问题,请参考以下文章