当前位置: 代码迷 >> J2SE >> 线程的同步,唤醒,等待的应用解决办法
  详细解决方案

线程的同步,唤醒,等待的应用解决办法

热度:215   发布时间:2016-04-24 02:31:57.0
线程的同步,唤醒,等待的应用
Java code
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();    }};

运行结果:
=====开始进水======
进水1分钟
进水2分钟
进水3分钟
进水4分钟
进水5分钟

这个题为什么只能进水不能放水呢啊?


------解决方案--------------------
虽然,你new了两个实例,这两个实例是完全不想干的,不在同一个线程。所以你在调用inwater的时候,虽然已经把flag置为true但是这个对outwaterh没有任何影响。
  相关解决方案