大神帮我看看自己写的多线程哪里出了问题
主要功能是两个线程操作一个变量,一个让它+1,一个让它-1然后交替输出
public class Res { private boolean flag = true; private int x = 1; public synchronized void print1() { if (!flag) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(x++); flag = false; this.notify(); } public synchronized void print2() { if (flag) { } try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(x--); flag = true; this.notify(); } }
public class PrintOne implements Runnable{ private Res r; public PrintOne(Res r){ this.r=r; } public void run(){ while(true){ r.print1(); } } }
public class PrintTwo implements Runnable{ private Res r; public PrintTwo(Res r){ this.r=r; } public void run(){ while(true){ r.print2(); } } }
public class Test { public static void main(String[] args) { Res r=new Res(); new Thread(new PrintOne(r)).start(); new Thread(new PrintTwo(r)).start(); } }
运行结果就是输出一个1,就停住了,哪里死锁了还是全部等待了