多线程顺序打印ABC

多线程顺序打印ABC
不断唤醒机制,借用重入锁和条件队列
package com.hnist.lzn.Java8;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/*
多线程顺序打印ABC

 */
//
public class PrintABC {

    int count = 0;

    Lock lock = new ReentrantLock();

    Condition conditionA = this.lock.newCondition();
    Condition conditionB = this.lock.newCondition();
    Condition conditionC = this.lock.newCondition();

    public class PrintA implements  Runnable{


        @Override
        public void run() {
            while(true){

                    System.out.println("--A---"+count);
                    lock.lock();
                    System.out.println("A");


                    try {
                        conditionB.signal();
                        conditionA.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }finally {
                        lock.unlock();
                    }


                }



        }
    }

    public class PrintB implements  Runnable{


        @Override
        public void run() {
            while(true){

                    System.out.println("--B---"+count);
                    lock.lock();
                    System.out.println("B");


                    try {
                        conditionC.signal();
                        conditionB.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }finally {
                        lock.unlock();
                    }





            }
        }
    }


    public class PrintC implements  Runnable{


        @Override
        public void run() {
            while(true){
                //if(count<10){
                    System.out.println("--C---"+count);
                    lock.lock();
                    System.out.println("C");


                    try {
                        conditionA.signal();
                        conditionC.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }finally {
                        lock.unlock();
                    }





            }
        }
    }

    public static void main(String[] args) {


        PrintABC printABC=new PrintABC();
        new Thread(printABC.new PrintA()).start();
        new Thread(printABC.new PrintB()).start();
        new Thread(printABC.new PrintC()).start();
    }



}

 

结论:    1.重入锁配合条件队列,每个条件队列的条件不一样。同时,每个条件都被锁住了。

      

 

你可能感兴趣的:(面试题多线程)