为了账号安全,请及时绑定邮箱和手机立即绑定

多线程怎么交替输出

多线程怎么交替输出

fenkapian 2018-05-03 20:28:14
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  但老不对 哪里错了啊
查看完整描述

2 回答

?
半枯

TA贡献101条经验 获得超45个赞

111

查看完整回答
反对 回复 2018-05-03
  • 2 回答
  • 0 关注
  • 1288 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信