Java 中使用多线程实现 奇数偶数交替使用线程输出

本文通过一个具体的案例,展示了如何使用synchronized关键字实现线程间的同步,确保奇数和偶数交替输出。通过创建数字提供类和两个线程类,分别负责输出奇数和偶数,实现了线程之间的正确同步。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

之前看老杜 JavaSE 教程时给的题目, 当时没做出来.

今天重看新版教程时正好看到 synchronized 关键字, 突然想出解决办法了, 做个记录.

 

思路:

写一个类做数字提供.

写两个线程类分别做奇数输出和偶数输出. 这两个类都会带一个 数字提供类 的实例.

主方法中构造一个数字提供对象, 和两个以此数字提供对象为构造参数的线程类对象.

 

代码实现:

package com.javalearn.thread;

public class SwitchPrint {
    public static void main(String[] args) {
        Printer p = new Printer();
        Thread t1 = new Thread(new PrintOdd(p));
        Thread t2 = new Thread(new PrintEven(p));

        t1.setName("奇数线程");
        t2.setName("偶数线程");

        t1.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t2.start();
    }
}

class Printer {
    private int i = 0;

    public int getI() {
        return i;
    }

    public int printI() {
        return i++;
    }
}

class PrintOdd implements Runnable {
    private Printer p;

    public PrintOdd(Printer p) {
        this.p = p;
    }

    @Override
    public void run() {
        while (p.getI()<100) {
            synchronized (p) {
                if (p.getI() % 2 == 0) {
                    try {
                        p.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(Thread.currentThread().getName() + "打印输出: " + p.printI());
                p.notify();
            }
        }
    }
}

class PrintEven implements Runnable {
    private Printer p;

    public PrintEven(Printer p) {
        this.p = p;
    }

    @Override
    public void run() {

        while(p.getI()<100) {
            synchronized (p) {
                if (p.getI() % 2 != 0) {
                    try {
                        p.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(Thread.currentThread().getName() + "打印输出: " + p.printI());
                p.notify();
            }

        }

    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值