- package org.yang;
- import java.util.concurrent.locks.Condition;
- import java.util.concurrent.locks.Lock;
- import java.util.concurrent.locks.ReentrantLock;
- public class Test {
- public static void main(String[] args) {
- final Businese b = new Businese();
- new Thread(new Runnable() {
- public void run() {
- while (true) {
- b.sub();
- }
- }
- }).start();
- new Thread(new Runnable() {
- public void run() {
- while (true) {
- b.sub2();
- }
- }
- }).start();
- new Thread(new Runnable() {
- public void run() {
- while (true) {
- b.main();
- }
- }
- }).start();
- }
- }
- class Businese {
- Lock lock = new ReentrantLock();
- Condition sub1Condition = lock.newCondition();
- Condition sub2Condition = lock.newCondition();
- Condition mainCondition = lock.newCondition();
- int isWho = 1;
- public void sub() {
- lock.lock();
- try {
- while (isWho != 2) {
- try {
- sub1Condition.await();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- System.out.println("老二在运行");
- this.isWho = 3;
- sub2Condition.signal();
- } finally {
- lock.unlock();
- }
- }
- public void sub2() {
- lock.lock();
- try {
- while (isWho != 3) {
- try {
- sub2Condition.await();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- System.out.println("老三在运行");
- this.isWho = 1;
- mainCondition.signal();
- } finally {
- lock.unlock();
- }
- }
- public void main() {
- lock.lock();
- try {
- while (this.isWho != 1) {
- try {
- mainCondition.await();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- System.out.println("老大在运行");
- this.isWho = 2;
- sub1Condition.signal();
- } finally {
- lock.unlock();
- }
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/120520149518.html
来源: http://www.codesnippet.cn/detail/120520149518.html