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();
????}
}我想兩個(gè)線(xiàn)程交替輸出1和2? 但老不對(duì) 哪里錯(cuò)了啊
添加回答
舉報(bào)
0/150
提交
取消