首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

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

2012-01-07 
线程的同步,唤醒,等待的应用Java codeclass Port{private boolean flag falsepublic synchronized void

线程的同步,唤醒,等待的应用

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没有任何影响。

热点排行