两个线程,一个线程打印1-52,另一个打印字母A-Z打印顺序为12A34B...5152Z, 要求用线程间通信

first boke

package com.atguigu.juc.FutureTaskTest;

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

/**

  • 用一个lock去锁不同的方法,每一condition完成以后,修改对应的条件变量,再唤醒另外需要执行的代码,
  • 注意在finally里面
  • @author yhfstart
  • @create 2018-12-28 0:43

*/
public class PrintTest {

public static void main(String[] args) {


   PrintTest1 printTest1 = new printTest1();

    new Thread((()->{
        printTest1.printA_Z();
    }),"打印A-Z线程").start();

    new Thread((()->{
        printTest1.print1_52();
    }),"打印1-52线程").start();


}

}

class PrintTest1 {

private static int num = 1;

public final Lock lock = new ReentrantLock();

public final Condition printA_ZCondition = lock.newCondition();
public final Condition print1_52Condition = lock.newCondition();

//打印数字的方法
public void print1_52() {
    lock.lock();
    try {
        for (int i = 1; i < 53; i++) {
            while (num%3==0){
                try {
                    print1_52Condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            System.out.println(Thread.currentThread().getName()+"=====>"+i);

            num++;



            printA_ZCondition.signal();

        }
    } finally {

        lock.unlock();
    }


}

//打印字母的方法
public void printA_Z() {

    lock.lock();

    try {
        for (char i = 'A'; i < 'Z'; i++) {
            //打印字母的方法

            while (num%3!=0){
                try {
                    printA_ZCondition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            System.out.println(Thread.currentThread().getName()+"=====+>"+i);
            //改条件,唤醒下一个线程
            num++;

            print1_52Condition.signal();

        }
    } finally {
        lock.unlock();
    }


}

}

你可能感兴趣的:(javaSE,javaee,多线程)