面试题:两个线程打印 ,一个线程打印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();
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值