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();
    }
}
相关推荐
欧阳秦穆10 分钟前
apoc-5.24.0-extended.jar 和 apoc-4.4.0.36-all.jar 啥区别
java·jar
好开心啊没烦恼13 分钟前
Python 数据分析:numpy,抽提,整数数组索引与基本索引扩展(元组传参)。听故事学知识点怎么这么容易?
开发语言·人工智能·python·数据挖掘·数据分析·numpy·pandas
岁忧21 分钟前
(LeetCode 面试经典 150 题 ) 58. 最后一个单词的长度 (字符串)
java·c++·算法·leetcode·面试·go
Java初学者小白25 分钟前
秋招Day14 - Redis - 应用
java·数据库·redis·缓存
代码老y31 分钟前
Spring Boot + 本地部署大模型实现:优化与性能提升
java·spring boot·后端
GodKeyNet35 分钟前
设计模式-桥接模式
java·设计模式·桥接模式
future14121 小时前
C#学习日记
开发语言·学习·c#
guojl1 小时前
Java多任务编排技术
java
丶意冷2 小时前
mybatisPlus分页方言设置错误问题 mybatisPlus对于Oceanbase的Oracle租户分页识别错误
java·数据库·oracle·oceanbase
king_harry2 小时前
Java程序-OceanBase Connector/J 示例
开发语言