概述
如下代码,执行多次,大部分程序会阻塞,不知道问题出现在哪,求教?
public class Main {
public static void main(String[] args) {
Serve s = new Serve();
Thread t1 = new Thread(new ThreadA(s));
Thread t2 = new Thread(new ThreadB(s));
t1.start();
t2.start();
}
}
class Serve {
private int count = 0;
private boolean hasCount = false;
public synchronized void addCount(int addCount) throws InterruptedException {
if(hasCount) {
wait();
System.out.println("add阻塞");
}else {
this.count += addCount;
hasCount = true;
notifyAll();
System.out.println("存钱,余额:" + this.count);
}
}
public synchronized void removeCount(int removeCount ) throws InterruptedException {
if(hasCount) {
this.count -= removeCount;
hasCount = false;
notifyAll();
System.out.println("取钱,余额:" + this.count);
}else {
wait();
System.out.println("remove阻塞");
}
}
}
class ThreadA implements Runnable {
private Serve s;
public ThreadA(Serve s) {
this.s = s;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
System.out.println("add" + i);
s.addCount(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class ThreadB implements Runnable {
private Serve s;
public ThreadB(Serve s) {
this.s = s;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
System.out.println("remove" + i);
s.removeCount(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
最后
以上就是无限煎蛋为你收集整理的java wait阻塞_wait/notify问题,为什么程序会阻塞?的全部内容,希望文章能够帮你解决java wait阻塞_wait/notify问题,为什么程序会阻塞?所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复