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(); }}
}
點擊查看更多內(nèi)容
為 TA 點贊
評論
評論
共同學(xué)習(xí),寫下你的評論
評論加載中...
作者其他優(yōu)質(zhì)文章
正在加載中
感謝您的支持,我會繼續(xù)努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進(jìn)行掃碼打賞哦