打印数字1-20,一个线程打印奇数,一个线程打印偶数

 

main.class

public class Solution1006 {
    public static void main(String[] args) {
        MyObject my = new MyObject();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i=0; i<10; i++)
                    my.printOdd();
            }
        },"奇数线程").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i=0; i<10; i++)
                    my.printEven();
            }
        },"偶数线程").start();
    }
}

MyObject.class

public class MyObject {

    private static int num = 1;

    public synchronized void printOdd(){
        while(num%2 == 0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println(Thread.currentThread().getName() + ": " + num);
        num++;
        this.notifyAll();
    }

    public synchronized void printEven(){
        while(num%2 != 0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println(Thread.currentThread().getName() + ": " + num);
        num++;
        this.notifyAll();
    }
}

结果:

打印数字1-20,一个线程打印奇数,一个线程打印偶数_第1张图片

你可能感兴趣的:(多线程编程)