public class Wahaha {
private int num;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public Wahaha(int num) {
super();
this.num = num;
}
public Wahaha() {
super();
// TODO Auto-generated constructor stub
}
}
public static Object obj = new Object();
public static void main(String[] args) {
Wahaha w = new Wahaha();
new Thread(new Runnable() {
@Override
public synchronized void run() {
while (true) {
synchronized (obj) {
if (w.getNum() > 9) {
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/*try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}*/
w.setNum(w.getNum() + 1);
System.out.println(Thread.currentThread().getName() + "了1瓶娃哈哈,仓库有" + w.getNum() + "瓶娃哈哈");
obj.notify();
}
}
}
}, "生产2 ").start();
new Thread(new Runnable() {
@Override
public synchronized void run() {
while (true) {
synchronized (obj) {
if (w.getNum() <= 0) {
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/*try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}*/
w.setNum(w.getNum() - 1);
System.out.println(Thread.currentThread().getName() + "了1瓶娃哈哈,仓库有" + w.getNum() + "瓶娃哈哈");
obj.notify();
}
}
}
}, "销售").start();
new Thread(new Runnable() {
@Override
public synchronized void run() {
while (true) {
synchronized (obj) {
if (w.getNum() > 9) {
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/*try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}*/
w.setNum(w.getNum() + 1);
System.out.println(Thread.currentThread().getName() + "了1瓶娃哈哈,仓库有" + w.getNum() + "瓶娃哈哈");
obj.notify();
}
}
}
}, "生产1 ").start();
}
运行结果如下
销售了1瓶娃哈哈,仓库有574瓶娃哈哈
销售了1瓶娃哈哈,仓库有573瓶娃哈哈
销售了1瓶娃哈哈,仓库有572瓶娃哈哈
销售了1瓶娃哈哈,仓库有571瓶娃哈哈
销售了1瓶娃哈哈,仓库有570瓶娃哈哈
生产1 了1瓶娃哈哈,仓库有571瓶娃哈哈
销售了1瓶娃哈哈,仓库有570瓶娃哈哈
销售了1瓶娃哈哈,仓库有569瓶娃哈哈
销售了1瓶娃哈哈,仓库有568瓶娃哈哈
销售了1瓶娃哈哈,仓库有567瓶娃哈哈
销售了1瓶娃哈哈,仓库有566瓶娃哈哈
销售了1瓶娃哈哈,仓库有565瓶娃哈哈
销售了1瓶娃哈哈,仓库有564瓶娃哈哈
销售了1瓶娃哈哈,仓库有563瓶娃哈哈
销售了1瓶娃哈哈,仓库有562瓶娃哈哈
销售了1瓶娃哈哈,仓库有561瓶娃哈哈
生产2 了1瓶娃哈哈,仓库有562瓶娃哈哈
销售了1瓶娃哈哈,仓库有561瓶娃哈哈
销售了1瓶娃哈哈,仓库有560瓶娃哈哈
销售了1瓶娃哈哈,仓库有559瓶娃哈哈
销售了1瓶娃哈哈,仓库有558瓶娃哈哈
销售了1瓶娃哈哈,仓库有557瓶娃哈哈
销售了1瓶娃哈哈,仓库有556瓶娃哈哈
销售了1瓶娃哈哈,仓库有555瓶娃哈哈
销售了1瓶娃哈哈,仓库有554瓶娃哈哈
销售了1瓶娃哈哈,仓库有553瓶娃哈哈
销售了1瓶娃哈哈,仓库有552瓶娃哈哈
销售了1瓶娃哈哈,仓库有551瓶娃哈哈
销售了1瓶娃哈哈,仓库有550瓶娃哈哈
销售了1瓶娃哈哈,仓库有549瓶娃哈哈
销售了1瓶娃哈哈,仓库有548瓶娃哈哈
为什么单层锁可以控制线程安全,但是放在一起以后就失效了呢?