两个线程,一个打印奇数,一个打印偶数,连续输出1-100

/**
 * 两个线程,一个打印奇数,一个打印偶数,连续输出1-100
 * Created by vendetta on 2018/8/31.
 */
public class OddAndEven {
    //state==1表示线程1开始打印,state==2表示线程2开始打印
    private static int state = 1;

    private static int odd = 1;
    private static int even = 0;

    public static void main(String[] args) {
        OddAndEven oddAndEven = new OddAndEven();

        new Thread(() -> {
            while (odd <= 100){
                synchronized (oddAndEven){
                    if (state !=1){
                        try {
                            oddAndEven.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println(odd);
                    odd += 2;
                    state = 2;
                    oddAndEven.notifyAll();
                }
            }
        }).start();

        new Thread(() -> {
            while (even <= 100){
                synchronized (oddAndEven){
                    if (state !=2){
                        try {
                            oddAndEven.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println(even);
                    even += 2;
                    state = 1;
                    oddAndEven.notifyAll();
                }
            }
        }).start();
    }

}

输出结果:

1
2
3
...
97
98
100

你可能感兴趣的:(两个线程,一个打印奇数,一个打印偶数,连续输出1-100)