Java 两个线程交替打印1-100

线程题:交替打印1-100

这里演示两个线程,一个打印奇数,一个打印偶数

方式一:synchronized + FixedThreadPool
public class example {

    private static int count = 1;

    private static final Object lock = new Object();
    public static void main(String[] args) {
        ThreadFactory factory = new ThreadFactory() {
            AtomicInteger ai = new AtomicInteger(1);
            @Override
            public Thread newThread(@NotNull Runnable r) {
                Thread thread = new Thread(r, ai.getAndIncrement() + ": ");
                return thread;
            }
        };
        ExecutorService executorService = Executors.newFixedThreadPool(2, factory);
        executorService.submit(example::printOdd);
        executorService.submit(example::printEven);

    }

    private static void printOdd() {
        while (count <= 100) {
            synchronized (lock) {
                if(count % 2 != 0 && count <= 100) {
                    System.out.println(Thread.currentThread().getName() + ": " + count);
                    count++;
                }
            }
        }
    }

    private static void printEven() {
        while (count <= 100) {
            synchronized (lock) {
                if(count % 2 == 0 && count <= 100) {
                    System.out.println(Thread.currentThread().getName() + ": " + count);
                    count++;
                }
            }
        }
    }
}
方法二:ReentrantLock + Condition
public class example2 {

    static ReentrantLock lock = new ReentrantLock();


    static int count = 1;
    public static void main(String[] args) {
        // 两个 condition
        Condition odd = lock.newCondition();
        Condition even = lock.newCondition();

        new Thread(() -> {
            while(count <= 100) {
                lock.lock();
                try {
                    try {
                        if (count % 2 != 0) {
                            System.out.println(Thread.currentThread().getName() + ": " + count);
                            count++;
                        }
                        even.signal();
                        odd.await();

                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }finally {
                    lock.unlock();
                }
            }
        }, "odd").start();

        new Thread(() -> {
            while(count <= 100) {
                lock.lock();
                try {
                    try {
                        if (count % 2 == 0) {
                            System.out.println(Thread.currentThread().getName() + ": " + count);
                            count++;
                        }
                        odd.signal();
                        even.await();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }finally {
                    lock.unlock();
                }
            }
        }, "even").start();
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中,我们可以使用 `synchronized` 关键字和 `wait()`、`notify()` 方法来实现线程交替输出。下面是一个示例代码: ```java class OddEvenPrinter { private int count; private int maxCount; public OddEvenPrinter(int maxCount) { this.maxCount = maxCount; this.count = 1; } public synchronized void printOdd() throws InterruptedException { while (count <= maxCount) { if (count % 2 != 0) { System.out.println(count); count++; notify(); } else { wait(); } } } public synchronized void printEven() throws InterruptedException { while (count <= maxCount) { if (count % 2 == 0) { System.out.println(count); count++; notify(); } else { wait(); } } } } public class Main { public static void main(String[] args) { OddEvenPrinter printer = new OddEvenPrinter(100); Thread oddThread = new Thread(() -> { try { printer.printOdd(); } catch (InterruptedException e) { e.printStackTrace(); } }); Thread evenThread = new Thread(() -> { try { printer.printEven(); } catch (InterruptedException e) { e.printStackTrace(); } }); oddThread.start(); evenThread.start(); } } ``` 在这个代码中,我们创建了一个名为 `OddEvenPrinter` 的类,它有一个 `count` 变量来表示当前要输出的数字,和一个 `maxCount` 变量来表示最大的数字。`printOdd()` 方法用于输出奇数,`printEven()` 方法用于输出偶数。 在每个方法中,我们使用 `synchronized` 关键字来确保线程的同步。在 `printOdd()` 方法中,当 `count` 为奇数时输出数字并递增,然后调用 `notify()` 方法唤醒等待的线程;如果 `count` 为偶数,则调用 `wait()` 方法使线程等待。在 `printEven()` 方法中同理。 在 `main()` 方法中,我们创建了两个线程 `oddThread` 和 `evenThread`,分别执行 `printOdd()` 和 `printEven()` 方法。然后启动这两个线程,它们将交替输出奇偶数

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值