ABC

2017-12-21  本文已影响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();

}

}

}

}

上一篇 下一篇

猜你喜欢

热点阅读