1. 程式人生 > >列印數字1-20,一個執行緒列印奇數,一個執行緒列印偶數

列印數字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();
    }
}