Java多线程按顺序输出10以内的奇偶数

创建两个线程,一个线程输出奇数,一个线程输出偶数,实现按照1~10的顺序输出

代码实现1

java 复制代码
public class OddEvenNumber {
    // volatile关键字修饰的变量保证了可见性,即对该变量的写操作对其他线程可见。
    private volatile int num = 1;
    public static void main(String[] args) {
        OddEvenNumber number = new OddEvenNumber();
        new Thread(() -> number.technology()).start();
        new Thread(() -> number.even()).start();
    }

    public synchronized void technology() {
        while (num < 11) {
            if (num % 2 != 0) {
                System.out.println(num);
                num++;
            } else {
                notify();
                try {
                    wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    public synchronized void even() {
        while (num < 11) {
            if (num % 2 == 0) {
                System.out.println(num);
                num++;
            } else {
                notify();
                try {
                    wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}

代码实现2

java 复制代码
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadPoolExecutorExample {
    public static void main(String[] args) {
        // 核心线程数为2,最大线程数为2,线程空闲时间为10秒,使用无边界队列
        // 使用默认的线程工厂和饱和策略
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                2, 2, 1, TimeUnit.SECONDS, new LinkedBlockingDeque<>() //, new ThreadPoolExecutor.CallerRunsPolicy()
        );

        // 提交任务给线程池执行
        // submit()方法也接受一个 Runnable 对象作为参数,但它返回一个 Future 对象,用于异步获取任务执行结果或者取消任务执行。
        // 方法没有返回值,如果任务执行过程中出现异常或错误,它不会抛出该异常或错误,只会简单地打印出异常栈信息。

        AtomicInteger num = new AtomicInteger(1);  // 初始值为1,线程安全的,原子类

        executor.submit(() -> {
            while (num.get() <= 10) {
                if (num.get() % 2 == 0) {
                    System.out.println(num.get());
                    num.incrementAndGet();  // 等同于 num++
                }
            }
        });
        // execute()方法接受一个 Runnable 对象作为参数,将其提交到线程池中执行。
        // 方法没有返回值,如果任务执行过程中出现异常或错误,它不会抛出该异常或错误,只会简单地打印出异常栈信息。
        executor.execute(() -> {
            while (num.get() < 10) {
                if (num.get() % 2 != 0) {
                    System.out.println(num.get());
                    num.incrementAndGet();  // 等同于 num++
                }
            }
        });

        //关闭线程池
        executor.shutdown();
    }
}
相关推荐
嵌入式进阶行者8 小时前
【算法】基于滑动窗口的区间问题求解算法与实例:华为OD机考双机位A卷 - 最长的顺子
开发语言·c++·算法
小宇的天下8 小时前
Calibre 3Dstack --每日一个命令day7【Centers】(3-7)
java·服务器·数据库
用户0304805912638 小时前
Spring Boot 配置文件加载大揭秘:优先级覆盖与互补合并机制详解
java·后端
青莲8438 小时前
Java内存回收机制(GC)完整详解
java·前端·面试
No0d1es8 小时前
2025年12月 GESP CCF编程能力等级认证Python三级真题
开发语言·php
CRUD酱8 小时前
微服务分模块后怎么跨模块访问资源
java·分布式·微服务·中间件·java-ee
gAlAxy...8 小时前
5 种 SpringBoot 项目创建方式
java·spring boot·后端
lalala_lulu8 小时前
什么是事务,事务有什么特性?
java·开发语言·数据库
CCPC不拿奖不改名8 小时前
python基础:python语言中的函数与模块+面试习题
开发语言·python·面试·职场和发展·蓝桥杯
毕设源码-朱学姐8 小时前
【开题答辩全过程】以 基于Python语言的疫情数据可视化系统为例,包含答辩的问题和答案
开发语言·python·信息可视化