/** * @param args */ public static void main(String[] args) { final Utils ts = new Utils(); new Thread(){ @Override public void run() { for (int i = 0; i < 30; i++) { ts.sub(i); } } }.start();
for (int i = 0; i < 30; i++) { ts.main(i); } }
}
class Utils{
private boolean flag = true;
public synchronized void main(int j){ if(!flag){ try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } for (int i = 1; i <= 5; i++) { System.out.println(j+":this's main"+i); } this.flag = false; this.notify(); }
public synchronized void sub(int j){ if(flag){ try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } for (int i = 1; i <= 10; i++) { System.out.println(j+":this's sub"+i); } this.flag = true; this.notifyAll(); } }