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分钟这个题为什么只能进水不能放水呢啊?
改成:
private static boolean flag = false;