源码如下:
public class TakeAndPour {
public static void main(String args[]) {
WaterTaking wt = new WaterTaking();
WaterPouring wp = new WaterPouring();
Thread t1 = new Thread(wt, "Xiaohao");
Thread t2 = new Thread(wp, "doubi");
t1.start();
t2.start();
}
}
class Tank {
private static int count = 10; // 缸里原有的水
//private static int max = 5;
private static boolean flag = true; //防止同时取水、 倒入水
public void takeWater() {
synchronized (this) {
while (!flag) {
try {
System.out
.println("The tank is being used now");
this.wait();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
flag = false; //同一时刻只允许一个对水缸操作
try {
Thread.sleep(800);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
count--;
System.out.println(flag+" "+Thread.currentThread().getName()
+ " take out some water" + " now water remain " + count);
flag = true;
this.notifyAll(); //操作完了就把flag置为true,并唤醒线程,这里使用notify()一样。
}
}
public void pourWater() {
synchronized (this) {
flag = false;
while (!flag) {
try {
System.out
.println("the tank is being used");
this.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
try {
Thread.sleep(800);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
count++;
System.out.println(flag+" "+Thread.currentThread().getName()
+ " pour in some water" + " now water remain " + count);
flag = true;
this.notifyAll();
}
}
}
class WaterTaking implements Runnable {
Tank t = new Tank();
public void run() {
while(true){
t.takeWater();
}
}
}
class WaterPouring implements Runnable {
Tank t = new Tank();
public void run() {
while(true){
t.pourWater();
}
}
}
但是 现在的结果出现了问题,打印如下:
the tank is being used, or the tank is full of water.
false Xiaohao take out some water now water remain 9
false Xiaohao take out some water now water remain 8
false Xiaohao take out some water now water remain 7
false Xiaohao take out some water now water remain 6
false Xiaohao take out some water now water remain 5
false Xiaohao take out some water now water remain 4
false Xiaohao take out some water now water remain 3
.......
倒入水的线程,第一下进去就被卡住了,全是取水的线程。求各位帮下忙分析下问题所在,谢了!
------解决思路----------------------
同步就是许多线程同时用一个资源啥的哦,一个在用别的就要等,异步就相反了,可以不用等待
先搞清楚同步异步的含义吧 概念混淆
还有 你这个水可以放城负数也是够了 count的值都没有判断下 修改flag 来控制