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 分钟前
02.Golang 切片(slice)源码分析(一、定义与基础操作实现)
开发语言·后端·python·golang
purrrew42 分钟前
【Java ee初阶】初始网络
java·网络
程序员Bears1 小时前
从零打造个人博客静态页面与TodoList应用:前端开发实战指南
java·javascript·css·html5
Helibo441 小时前
GESPC++六级复习
java·数据结构·算法
serve the people1 小时前
解决osx-arm64平台上conda默认源没有提供 python=3.7 的官方编译版本的问题
开发语言·python·conda
柒七爱吃麻辣烫2 小时前
在Linux中安装JDK并且搭建Java环境
java·linux·开发语言
极小狐2 小时前
极狐GitLab 容器镜像仓库功能介绍
java·前端·数据库·npm·gitlab
极小狐2 小时前
如何构建容器镜像并将其推送到极狐GitLab容器镜像库?
开发语言·数据库·机器学习·gitlab·ruby
努力的搬砖人.2 小时前
如何让rabbitmq保存服务断开重连?保证高可用?
java·分布式·rabbitmq
_星辰大海乀3 小时前
数据库约束
java·数据结构·数据库·sql·链表