多线程-等待唤醒+代码优化
public class beginning { public static void main(String[] args) { Res r = new Res(); new Thread(new Test(r)).start(); new Thread(new TestDemo(r)).start(); } } class Test implements Runnable { Res r = new Res(); Test(Res r) { this.r = r; } public void run() { int x = 0; while(true) { if(x==0) { r.set("mike....", "nan..."); }else { r.set("里斯+++++","女女女女女+++++"); } x = (x+1)%2; } } } class TestDemo implements Runnable { Res r = new Res(); TestDemo(Res r) { this.r = r; } public void run() { while(true) { r.out(); } } } class Res { private boolean flag = false; private String name; private String sex; public synchronized void set(String name ,String sex) { if(flag) { try{this.wait();}catch(Exception e) {} } this.name = name; this.sex = sex; flag = true; this.notify(); } public synchronized void out() { if(!flag) { try{this.wait();}catch(Exception e) {} } System.out.println(this.name+"......"+this.sex); flag = false; this.notify(); } }
作者:张小龙 一个不安定的程序猿