如何交替打印输出0~100

本文对比了使用`synchronized`和`ReentrantLock`+`Condition`在Java中实现的三个线程交替打印0-100的场景,探讨了两种同步机制的异同和适用性。

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

两个线程交替打印0~100

synchronized

public class JUCTest {

    private static final Object monitor = new Object();
    private static volatile int count = 0;
    private static final int MAX = 100;

    public static void main(String[] args) {
        Thread t1 = new Thread(new Print(), "thread-1");
        Thread t2 = new Thread(new Print(), "thread-2");
        t1.start();
        t2.start();
    }

    static class Print implements Runnable {

        @Override
        public void run() {
            while (count <= MAX) {
                synchronized (monitor) {
                    try {
                        if (count <= MAX) {
                            System.out.println(Thread.currentThread().getName() + ": " + count);
                            count++;
                        }
                        monitor.notifyAll();
                        monitor.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }

        }
    }
}

ReentrantLock

public class JUCTest {

    private static volatile int count = 0;
    private static final int MAX = 100;
    
    private static final ReentrantLock lock = new ReentrantLock();
    private static final Condition condition = lock.newCondition();

    public static void main(String[] args) {
        Thread t1 = new Thread(new Print(), "thread-1");
        Thread t2 = new Thread(new Print(), "thread-2");
        t1.start();
        t2.start();
    }

    static class Print implements Runnable {

        @Override
        public void run() {
            while (count <= MAX) {
                lock.lock();
                try {
                    if (count <= MAX) {
                        System.out.println(Thread.currentThread().getName() + ": " + count);
                        count++;
                    }
                    condition.signalAll();
                    condition.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }

        }
    }
}

三个线程交替打印0~100

synchronized

// synchronized + Monitor
public class JUCTest {

    private static final Object monitor = new Object();
    private static volatile int count = 0;
    private static final int MAX = 100;

    public static void main(String[] args) {
        Thread t1 = new Thread(new Print(0));
        Thread t2 = new Thread(new Print(1));
        Thread t3 = new Thread(new Print(2));
        t1.start();
        t2.start();
        t3.start();
    }

    static class Print implements Runnable {

        private final int seq;

        public Print(int seq) {
            this.seq = seq;
        }

        @Override
        public void run() {
            while (count <= MAX){
                synchronized (monitor) {
                    // 注意这里是 while,不是 if
                    while (count % 3 != seq) {
                        try {
                            monitor.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    if(count <= MAX){
                        System.out.println("thread-" + seq + ": " + count);
                        count++;
                    }
                    monitor.notifyAll();
                }
            }

        }
    }
}


ReentrantLock

// ReentrantLock + Condition
public class JUCTest {

    private static volatile int count = 0;
    private static final int MAX = 100;

    private static final ReentrantLock lock = new ReentrantLock();
    private static final Condition condition = lock.newCondition();


    public static void main(String[] args) {
        Thread t1 = new Thread(new Print(0));
        Thread t2 = new Thread(new Print(1));
        Thread t3 = new Thread(new Print(2));
        t1.start();
        t2.start();
        t3.start();
    }

    static class Print implements Runnable {

        private final int seq;

        public Print(int seq) {
            this.seq = seq;
        }

        @Override
        public void run() {
            while (count <= MAX) {
                lock.lock();
                // 注意这里是 while,不是 if
                while (count % 3 != seq) {
                    try {
                        condition.await();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                if (count <= MAX) {
                    System.out.println("thread-" + seq + ": " + count);
                    count++;
                }
                condition.signalAll();
            }
        }

    }
}
好的,这是一个使用Java编写的应用程序,创建两个线程,一个线程打印输出1~1000之间所有的奇数,另一个线程打印输出1~1000之间所有的偶数,要求两个线程随机休眠一段时间后继续打印输出下一个数。请使用Thread类编程实现。 ```java public class ThreadDemo { public static void main(String[] args) { Thread oddThread = new Thread(new OddNumber()); Thread evenThread = new Thread(new EvenNumber()); oddThread.start(); evenThread.start(); } } class OddNumber implements Runnable { @Override public void run() { for (int i = 1; i <= 1000; i += 2) { System.out.println("Odd: " + i); try { Thread.sleep((long) (Math.random() * 1000)); } catch (InterruptedException e) { e.printStackTrace(); } } } } class EvenNumber implements Runnable { @Override public void run() { for (int i = 2; i <= 1000; i += 2) { System.out.println("Even: " + i); try { Thread.sleep((long) (Math.random() * 1000)); } catch (InterruptedException e) { e.printStackTrace(); } } } } ``` 在这个程序中,我们使用了Java中的Thread类创建了两个线程,一个是奇数线程,一个是偶数线程。每个线程都实现了Runnable接口,并重写了run()方法。在run()方法中,我们使用for循环打印输出1~1000之间的奇数或偶数,然后使用Thread.sleep()方法随机休眠一段时间。这样,两个线程就可以交替打印输出奇数和偶数了。 注意,在使用Thread.sleep()方法时需要捕获InterruptedException异常。此外,我们使用Math.random()方法生成了一个随机数来确定休眠时间,这里我们将其乘以1000,以毫秒为单位。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值