两个线程分别打印0-100的之间的奇偶数(两种方式对比)

业务描述

前段时间遇到一个题目,关于两个线程分别打印0-100的之间的奇偶数,当时自己的写法是通过synchronized同步锁结合wait 和notify 的方式进行编写。主要逻辑的代码如下所示:

package com.xyq.maventest.alibaba;

import java.util.concurrent.CountDownLatch;

/****
 * 两个线程分别打印0-100之间的奇偶数
 * @author youqiang.xiong
 * <p> TODO 简单描述此类的用途</p>
 * 2018年2月25日下午6:18:34
 */
public class ThreadPrintData {
   
   

    public static CountDownLatch latch = new CountDownLatch(2);

    private static Object lock = new Object();

    private static volatile Integer i = 0;
    private static final int TOTAL = 100;


    public static void main(String[] args) {

        Thread thread1 = new Thread() {

            @Override
            public void run() {
                while (i <= TOTAL) {
                    synchronized (lock) {
                        if (i % 2 == 1) {
                            System.out.println(Thread.currentThread().getName() + "打印:   " + i++);
                        } else {
                            lock.notifyAll();
                            try {
                                if(i <= TOTAL){
                                    lock.wait();
                                }
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }

            
在Java中,可以使用两种常见的方法来创建线程并同时打印1-1000范围内的奇数和偶数: 1. **匿名内部类(Thread 实现 Runnable 接口)**: ```java class PrintNumbers implements Runnable { private boolean isOdd; public PrintNumbers(boolean isOdd) { this.isOdd = isOdd; } @Override public void run() { for (int i = 1; i <= 1000; i++) { if ((isOdd && i % 2 != 0) || (!isOdd && i % 2 == 0)) { System.out.println(Thread.currentThread().getName() + ": " + i); } } } } public class Main { public static void main(String[] args) { Thread oddThread = new Thread(new PrintNumbers(true), "Odd"); Thread evenThread = new Thread(new PrintNumbers(false), "Even"); oddThread.start(); evenThread.start(); try { oddThread.join(); evenThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } } ``` 在这个例子中,我们创建了两个`PrintNumbers`线程,一个负责打印奇数,另一个打印偶数。 2. **实现 `Callable` 接口**: ```java import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class PrintNumbersCallable implements Callable<Integer> { private int start; public PrintNumbersCallable(int start, boolean isOdd) { this.start = start; } @Override public Integer call() throws Exception { for (int i = start; i <= 1000; i++) { if ((isOdd && i % 2 != 0) || (!isOdd && i % 2 == 0)) { System.out.println(Thread.currentThread().getName() + ": " + i); } } return null; } } public class Main { public static void main(String[] args) { ExecutorService executor = Executors.newFixedThreadPool(2); Future<?> futureOdd = executor.submit(new PrintNumbersCallable(1, true), "Odd"); Future<?> futureEven = executor.submit(new PrintNumbersCallable(2, false), "Even"); executor.shutdown(); try { futureOdd.get(); // 等待任务完成 futureEven.get(); // 等待另一个任务完成 } catch (ExecutionException | InterruptedException e) { e.printStackTrace(); } } } ``` 这里我们使用了`ExecutorService`和`Future`来异步地提交任务,并等待它们完成。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值