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

当我们使用两个线程交替打印时,使用Synchronized是很难做到的,所以这里我们使用Codition线程通信

Condition:查看API,java.util.concurrent.locks

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

/******************************************
 * Created with IntelliJ IDEA.
 * @Auther: Gryb
 * @Date: 2021/03/02/22:57
 * @Description:两个线程交替打印问题
 ******************************************/
public class test02 {
    static class ThreadExcutation{
        public Lock lock = new ReentrantLock();
        public Integer flag = 1;
        public int num = 1;
        public int AZ = 65;
        public Condition conditionNum = lock.newCondition();
        public Condition conditionAZ = lock.newCondition();

        public void printNum() throws InterruptedException {
            lock.lock();
            while (flag != 1) {
                conditionNum.await();
            }
            if (num % 2 == 1) {
                System.out.println(num);
                num++;
                flag = 1;
                conditionNum.signal();
            }else {
                System.out.println(num);
                num++;
                flag = 2;
                conditionAZ.signal();
            }
            lock.unlock();
        }


        public void printAZ() throws InterruptedException {
            lock.lock();
            while (flag != 2) {
                conditionAZ.await();
            }
            System.out.println((char)AZ);
            AZ++;
            flag = 1;
            conditionNum.signal();
            lock.unlock();
        }

        public static void main(String[] args) {
            ThreadExcutation threadExcutation = new ThreadExcutation();
            new Thread(()->{
                try {
                    for (int i = 0; i < 52; i++) {
                        threadExcutation.printNum();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
            new Thread(()->{
                try {
                    for (int i = 0; i < 26; i++) {
                        threadExcutation.printAZ();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页