首页 > 解决方案 > 通过两个类实现 Runnable 打印奇数和偶数,一个是奇数逻辑,另一个是偶数逻辑

问题描述

尝试通过 PrintOddClass 甚至通过 PrintEvenClass 打印奇数 我曾经通过 PrintOddEvenNumberTwoThreads 启动这两个线程,但无法实现它们。就像 1 2 3 4 等等在打印 1 2 之后我猜它会进入死锁状态。

也使用了 join() 方法,但它没有用。我只想通过这种方式实现这一目标。

public class PrintOddEvenNumberTwoThreads {
    public static void main(String[] args) throws InterruptedException {
        int N = 20;
        Thread t1 = new Thread(new PrintOddNumber(N), "OddThread");
        Thread t2 = new Thread(new PrintEvenNumber(N), "EvenThread");
        
        t1.start();
        t2.start();
    }
}

class PrintOddNumber implements Runnable {
    private int limit;
    private int num = 1;
    
    public PrintOddNumber(int limit) {
        this.limit = limit;
    }
    
    public void run() {
        synchronized(this) {
            while(num < limit) {
                if(num % 2 != 0) {
                    try {
                        System.out.println(num);
                        wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                num++;
                notify();
            }
        }
    }
}

class PrintEvenNumber implements Runnable {
    private int limit;
    private int num = 1;
    
    public PrintEvenNumber(int limit) {
        this.limit = limit;
    }
    public void run() {
        synchronized(this) {
            while(num < limit) {
                if(num % 2 == 0) {
                    System.out.println(num);
                    try {
                        wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                num++;
                notify();
            }
        }
    }
}

标签: javamultithreading

解决方案


推荐阅读