面试:双线程交替打印奇偶数

代码如下:

java 复制代码
package practice1;

/**
 * 0-100的奇数偶数打印
 * 1、通过对象的wait和notify进行线程阻塞
 * 2、通过对num%2的结果进行奇数偶数的判断输出
 *
 */
public class JiOuOne {

    private static volatile int num = 0;

    private static final int max = 100;

    public static void main(String[] args) {
        String monitor = "monitor";
        // 偶数线程
        Thread oddThread = new Thread(new OddNumber(monitor));
        oddThread.setName("偶数打印:");

        // 奇数线程
        Thread evenThread = new Thread(new EvenNumber(monitor));
        evenThread.setName("奇数打印:");

        oddThread.start();
        evenThread.start();
    }


    /**
     * 打印偶数
     */
    static class OddNumber implements Runnable {

        private String monitor;

        public OddNumber(String monitor) {
            this.monitor = monitor;
        }

        @Override
        public void run() {
            while (num <= max) {
                synchronized (monitor) {
                    // 如果num%2有余数,则除不尽,则阻塞
                    while (num % 2 != 0) {
                        try {
                            monitor.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println(Thread.currentThread().getName() + "->" + num);
                    num++;
                    // 唤醒监视器
                    monitor.notify();
                }
            }
        }
    }


    /**
     * 打印奇数
     */
    static class EvenNumber implements Runnable {

        private String monitor;

        public EvenNumber(String monitor) {
            this.monitor = monitor;
        }

        @Override
        public void run() {
            while (num < max) {
                synchronized (monitor) {
                    // 如果num%2余数为0,则可以除尽,阻塞
                    while (num % 2 == 0) {
                        try {
                            monitor.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println(Thread.currentThread().getName() + "->" + num);
                    num++;
                    // 唤醒对象监视器
                    monitor.notify();
                }
            }
        }
    }

}

运行结果:

相关推荐
2301_8166602121 小时前
PHP怎么处理Eloquent Attribute Inference属性推断_Laravel从数据自动推导类型【操作】
jvm·数据库·python
chools21 小时前
【AI超级智能体】快速搞懂工具调用Tool Calling 和 MCP协议
java·人工智能·学习·ai
李白你好21 小时前
TongWeb EJB 反序列化生成工具(Java-Chain 插件)
java·安全
_Evan_Yao21 小时前
技术成长周记06|面试中看清差距,新项目点燃热情
面试·职场和发展
qq_372154231 天前
Go 中自定义类型与基础类型的显式转换规则详解
jvm·数据库·python
U盘失踪了1 天前
Java 的 JAR 是什么?
java·jar
LiAo_1996_Y1 天前
CSS如何实现文字渐变效果_通过background-clip实现艺术字
jvm·数据库·python
2401_887724501 天前
CSS如何让表单在手机端友好展示_利用Flexbox实现堆叠排版
jvm·数据库·python
zhangchaoxies1 天前
Layui轮播图(carousel)怎么设置自动播放间隔
jvm·数据库·python
今天又在写代码1 天前
java-v2
java·开发语言