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();
    }
}
相关推荐
风与沙的较量丶39 分钟前
Java中的局部变量和成员变量在内存中的位置
java·开发语言
m0_7482517239 分钟前
SpringBoot3 升级介绍
java
水煮庄周鱼鱼1 小时前
C# 入门简介
开发语言·c#
编程星空1 小时前
css主题色修改后会多出一个css吗?css怎么定义变量?
开发语言·后端·rust
软件黑马王子1 小时前
Unity游戏制作中的C#基础(6)方法和类的知识点深度剖析
开发语言·游戏·unity·c#
Logintern092 小时前
使用VS Code进行Python编程的一些快捷方式
开发语言·python
Multiple-ji2 小时前
想学python进来看看把
开发语言·python
极客先躯2 小时前
说说高级java每日一道面试题-2025年2月13日-数据库篇-请说说 MySQL 数据库的锁 ?
java·数据库·mysql·数据库的锁·模式分·粒度分·属性分
程序员侠客行2 小时前
Spring事务原理 二
java·后端·spring
一个小白12 小时前
C++——list模拟实现
开发语言·c++