两个线程交替打印数字和字母,输出1A2B3C4D...

一、问题描述

实现一个程序,两个线程交替打印数字和字母,输出1A2B3C4D…,必须先打印数字。

正确输出结果:1A2B3C4D5E6F7G8H

二、3种解决方法

2.1、synchronized与wait/notify

import java.util.concurrent.atomic.AtomicBoolean;
/**
 * 交替打印字母与数字
 * 1A2B3C...
 * 保证先打印数字
 * @author IT00ZYQ
 * @date 2021/5/31 21:13
 **/
public class Q03_Synchronized_wait_notify {
    public static void main(String[] args) throws InterruptedException {
        Object lock = new Object();
        char[] cc = "ABCDEFGH".toCharArray();
        char[] nn = "12345678".toCharArray();
        // tag变量是为了保证数字线程先打印,防止出现A1B2...
        AtomicBoolean tag = new AtomicBoolean(false);

        new Thread(() -> {
            synchronized (lock) {
                for (int i = 0; i < nn.length; i++) {
                    tag.set(true);
                    System.out.print(nn[i]);
                    lock.notify();
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                // 没有最后的notify(),后打印字母的线程会一直处于阻塞状态,程序不会结束
                lock.notify();
            }
        }).start();


        new Thread(() -> {
            synchronized (lock) {
                while (!tag.get()) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                for (int i = 0; i < cc.length; i++) {
                    System.out.print(cc[i]);
                    lock.notify();
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }
}

2.2、LockSupport与park/unpark

import java.util.concurrent.locks.LockSupport;
/**
 * 交替打印字母与数字
 * 1A2B3C...
 * 保证先打印数字
 * @author IT00ZYQ
 * @date 2021/5/31 21:13
 **/
public class Q03_LockSupport_park_unpark {
    static Thread numThread = null, charThread = null;
    public static void main(String[] args) throws InterruptedException {
        char[] cc = "ABCDEFGH".toCharArray();
        char[] nn = "12345678".toCharArray();

        numThread = new Thread(() -> {
            for (int i = 0; i < nn.length; i++) {
                System.out.print(nn[i]);
                LockSupport.unpark(charThread);
                LockSupport.park();
            }
        });

        charThread = new Thread(() -> {
            for (int i = 0; i < cc.length; i++) {
                // 需要后打印字母,打印字母的线程应该先park(),保证数字线程已经先打印
                LockSupport.park();
                System.out.print(cc[i]);
                LockSupport.unpark(numThread);
            }
        });

        charThread.start();
        numThread.start();

    }
}

2.3、ReentrantLock与await/singal

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

/**
 * @author IT00ZYQ
 * @date 2021/5/31 21:40
 **/
public class Q03_ReentrantLock_condition {
    public static void main(String[] args) {
        char[] cc = "ABCDEFGH".toCharArray();
        char[] nn = "12345678".toCharArray();
        final ReentrantLock lock = new ReentrantLock();
        final Condition numCondition = lock.newCondition();
        final Condition charCondition = lock.newCondition();

        Thread numThread = new Thread(() -> {
            lock.lock();
            try {
                for (int i = 0; i < nn.length; i++) {
                    System.out.print(nn[i]);
                    // 唤醒字母线程
                    charCondition.signal();
                    // 数字线程阻塞
                    numCondition.await();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        });

        Thread charThread = new Thread(() -> {
            lock.lock();
            try {
                for (int i = 0; i < cc.length; i++) {
                	// 字母线程阻塞
                    charCondition.await();
                    System.out.print(cc[i]);
                    // 唤醒数字线程
                    numCondition.signal();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        });

        charThread.start();
        numThread.start();
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

it00zyq

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值