日期:2014-05-20 浏览次数:20734 次
class Port { private boolean flag = false; public synchronized void inWater(){ if(flag){ try{ super.wait(); }catch(Exception e){ e.printStackTrace(); } } int i=1; System.out.println("=====开始进水======"); while(i<=5){ try{ Thread.sleep(300); }catch(Exception e){ e.printStackTrace(); } System.out.println("进水"+i+"分钟"); i++; } flag = true; super.notify(); } public synchronized void outWater(){ if(!flag){ try{ super.wait(); }catch(Exception e){ e.printStackTrace(); } } int i=1; System.out.println("=====开始放水======"); while(i<=5){ try{ Thread.sleep(300); }catch(Exception e){ e.printStackTrace(); } System.out.println("放水"+i+"分钟"); i++; } flag = false; super.notify(); } }; class Inwater implements Runnable { Port port = new Port(); public void run(){ port.inWater(); } }; class Outwater implements Runnable { Port port = new Port(); public void run(){ port.outWater(); } }; public class ThreadDemo01 { public static void main(String[] args) { Inwater in = new Inwater(); Outwater out = new Outwater(); new Thread(in,"进水线程").start(); new Thread(out,"放水线程").start(); } };