我是靠谱客的博主 无限煎蛋,这篇文章主要介绍java wait阻塞_wait/notify问题,为什么程序会阻塞?,现在分享给大家,希望可以做个参考。

如下代码,执行多次,大部分程序会阻塞,不知道问题出现在哪,求教?

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内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(139)

评论列表共有 0 条评论

立即
投稿
返回
顶部