多线程怎么交替输出

package com.umbrella.container.queue;

public class TwoThread {
    static Word word = new Word();
    static class Word {
        boolean flag;
        int i;
        public Word() {
            this.flag = true;
            this.i = 0;
        }
    }
    public static void main(String[] args) {
        new Thread(() -> {
            while (word.i < 10) {
                synchronized (word) {
                    if (word.flag) {
                        try {
                            word.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        word.flag = false;
                        word.notify();
                        word.i++;
                        System.out.println(1);
                    }
                }
            }
        }).start();

        new Thread(() -> {
            while (word.i < 10) {
                synchronized (word) {
                    if (!word.flag) {
                        try {
                            word.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        word.flag = true;
                        word.notify();
                        word.i++;
                        System.out.println(2);
                    }
                }
            }
        }).start();
    }
}

我想两个线程交替输出1和2  但老不对 哪里错了啊

fenkapian
浏览 1289回答 2
2回答

半枯

111
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java