用程序实现两个线程交替打印 0~100 的奇偶数

本文介绍了一种使用SynchronousQueue实现两个线程交替打印0到100之间的奇数和偶数的方法。通过具体代码示例,展示了如何在Java中利用多线程和阻塞队列来完成这一任务。

用程序实现两个线程交替打印 0~100 的奇偶数


下班途中刷新闻时看到一道面试题:用程序实现两个线程交替打印 0~100 的奇偶数。
看到“多线程交替”字样,瞬间就想到了SynchronousQueue。闲言少叙,直接上代码:

import java.util.Optional;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;

public class CrossPrint {
    private static final int MAX = 100;

    public static void main(String[] args) {
        BlockingQueue<Integer> queue = new SynchronousQueue<>();
        new Thread(new PrintTask("Odd ", queue, true)).start();
        new Thread(new PrintTask("Even", queue, false)).start();
    }

    private static class PrintTask implements Runnable {
        private String name;
        private BlockingQueue<Integer> queue;
        private boolean start;
        private int value = -1;

        PrintTask(String name, BlockingQueue<Integer> queue, boolean start) {
            this.name = name;
            this.queue = queue;
            this.start = start;
        }

        @Override
        public void run() {
            while (value < MAX) {
                try {
                    if (start) {
                        putValue();
                        takeValue();
                    } else {
                        takeValue();
                        putValue();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        private void putValue() throws InterruptedException {
            queue.put(++value);
        }

        private void takeValue() throws InterruptedException {
            value = queue.take();
            Optional.of(value).filter(it -> it <= MAX)
                    .ifPresent(it -> System.out.println(name + ":" + it));
        }
    }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值