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分钟这个题为什么只能进水不能放水呢啊?

解决方案 »

  1.   

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

  2.   

    把private boolean flag = false;
    改成:
    private static boolean flag = false;
      

  3.   

    回复二楼,那样是不对的,因为你每次使用的还是原来的那个flag,新建的对象就是一个,每次都是一样的
      

  4.   

    要设成static,否则两个对象的运行相互之间是独立的,不会产生任何影响