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 但老不对 哪里错了啊
半枯
相关分类