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();
    }
}
相关推荐
重生之我在20年代敲代码4 分钟前
strncpy函数的使用和模拟实现
c语言·开发语言·c++·经验分享·笔记
爱上语文6 分钟前
Springboot的三层架构
java·开发语言·spring boot·后端·spring
serve the people9 分钟前
springboot 单独新建一个文件实时写数据,当文件大于100M时按照日期时间做文件名进行归档
java·spring boot·后端
qmx_071 小时前
HTB-Jerry(tomcat war文件、msfvenom)
java·web安全·网络安全·tomcat
为风而战1 小时前
IIS+Ngnix+Tomcat 部署网站 用IIS实现反向代理
java·tomcat
编程零零七2 小时前
Python数据分析工具(三):pymssql的用法
开发语言·前端·数据库·python·oracle·数据分析·pymssql
技术无疆3 小时前
快速开发与维护:探索 AndroidAnnotations
android·java·android studio·android-studio·androidx·代码注入
2401_858286113 小时前
52.【C语言】 字符函数和字符串函数(strcat函数)
c语言·开发语言
铁松溜达py3 小时前
编译器/工具链环境:GCC vs LLVM/Clang,MSVCRT vs UCRT
开发语言·网络
everyStudy3 小时前
JavaScript如何判断输入的是空格
开发语言·javascript·ecmascript