ABC

作者: 溯洄的_鲤鱼 | 来源:发表于2017-12-21 11:44 被阅读32次

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.locks.Condition;

import java.util.concurrent.locks.Lock;

import java.util.concurrent.locks.ReentrantLock;

public class Main {

private static final Lock LOCK = new ReentrantLock();

private static final Condition A = LOCK.newCondition();

private static final Condition B = LOCK.newCondition();

private static final Condition C = LOCK.newCondition();

private static int flag;

private static int max;

public static void main(String[] args) {

Main.max = 10;

ExecutorService pool = Executors.newFixedThreadPool(3);

pool.submit(new Main().new AThread());

pool.submit(new Main().new BThread());

pool.submit(new Main().new CThread());

pool.shutdown();

}

class AThread implements Runnable {

@Override

public void run() {

LOCK.lock();

try{

for(int x = 0; x < max; x++){

if (flag % 3 != 0) {

try {

A.await();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

System.out.println("A ");

flag++;

B.signal();

}

}finally{

LOCK.unlock();

}

}

}

class BThread implements Runnable {

@Override

public void run() {

LOCK.lock();

try{

for(int x = 0; x < max; x++){

if (flag % 3 != 1) {

try {

B.await();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

System.out.println("B");

flag++;

C.signal();

}

}finally{

LOCK.unlock();

}

}

}

class CThread implements Runnable {

@Override

public void run() {

LOCK.lock();

try{

for(int x = 0; x < max; x++){

if (flag % 3 != 2) {

try {

C.await();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

System.out.println("C ");

flag++;

A.signal();

}

}finally{

LOCK.unlock();

}

}

}

}

相关文章

网友评论

      本文标题:ABC

      本文链接:https://www.haomeiwen.com/subject/ymoowxtx.html