编写一个程序开启三个线程分别为ABC,每个线程将自己的Id在屏幕上打印十次,要求输出结果必须按照顺序ABCABCABC....

package JUC;

import java.util.concurrent.locks.Condition;

import java.util.concurrent.locks.Lock;

import java.util.concurrent.locks.ReentrantLock;

/**

* 编写一个程序开启三个线程分别为ABC,每个线程将自己的Id在屏幕上打印十次,要求输出结果必须按照顺序ABCABCABC....

*/

public class TestAlternate {

public static void main(String[] args){

final Alternate ad =new Alternate();

      new Thread(new Runnable() {

@Override

          public void run() {

for (int j=1;j<=20;j++) {

ad.functionA(j);

              }

}

},"A").start();

        new Thread(new Runnable() {

@Override

            public void run() {

for (int j=1;j<=20;j++) {

ad.functionB(j);

                }

}

},"B").start();

        new Thread(new Runnable() {

@Override

            public void run() {

for (int j=1;j<=20;j++) {

ad.functionC(j);

                }

}

},"C").start();

    }

}

class Alternate  {

int number =1 ;

    Locklock =new ReentrantLock();

    Conditioncondition1 =lock.newCondition();

    Conditioncondition2 =lock.newCondition();

    Conditioncondition3 =lock.newCondition();

    void functionA(int loapTime){

try{

lock.lock();

            if (number!=1){

condition1.await();

            }

for (int i=1; i<=10;i++){

System.out.println(Thread.currentThread().getName()+":"+"\t"+i+"\t"+loapTime);

            }

number =2;

            condition2.signal();

        }catch (InterruptedException e){

}finally {

lock.unlock();

        }

}

void functionB(int loapTime){

try{

lock.lock();

            if (number!=2){

condition2.await();

            }

for (int i=1; i<=10;i++){

System.out.println(Thread.currentThread().getName()+":"+"\t"+i+"\t"+loapTime);

            }

number =3;

            condition3.signal();

        }catch (InterruptedException e){

}finally {

lock.unlock();

        }

}

void functionC(int loapTime){

try{

lock.lock();

            if (number!=3){

condition3.await();

            }

for (int i=1; i<=10;i++){

System.out.println(Thread.currentThread().getName()+":"+"\t"+i+"\t"+loapTime);

            }

number =1;

            condition1.signal();

        }catch (InterruptedException e){

}finally {

lock.unlock();

        }

}

}

你可能感兴趣的:(编写一个程序开启三个线程分别为ABC,每个线程将自己的Id在屏幕上打印十次,要求输出结果必须按照顺序ABCABCABC....)