java检测线程运行失败_java多线程之间协作运行时没有任何结果没有任何错误信息,麻烦看下代码?...

使用 wait() 和 notifyAll() 方法编写一个多线程协作的案例,测试运行时,运行了第二个线程之后,其余的两个线程就没有执行。

public class House {

private boolean hasFoundation = false; // 地基

private boolean hasFrame = false; // 房屋框架

private boolean hasWall = false; // 墙

private boolean hasRoof = false; // 屋顶

public synchronized void buildFoundation() {

hasFoundation = true;

System.out.println("地基打好啦!");

notifyAll();

}

public synchronized void buildFrame() throws InterruptedException {

if (!hasFoundation) {

wait();

} else {

hasFrame = true;

System.out.println("框架搭好啦!");

notifyAll();

}

}

public synchronized void buildWall() throws InterruptedException {

if (!hasFrame) {

wait();

} else {

hasWall = true;

System.out.println("墙砌好啦!");

notifyAll();

}

}

public synchronized void buildRoof() throws InterruptedException {

if (!hasWall) {

wait();

} else {

hasRoof = true;

System.out.println("屋顶盖好啦!");

notifyAll();

}

}

}

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

public class BuildAHouse {

public static void main(String[] args) {

House house = new House();

ExecutorService exec = Executors.newCachedThreadPool();

exec.execute(new FoundationTeam(house));

exec.execute(new WallTeam(house));

exec.execute(new RoofTeam(house));

exec.execute(new FrameTeam(house));

exec.shutdown();

}

}

另外还有四个类,也就是 FoundationTeam等四个类,分别时实现了 Runnable接口,然后在run()方法中调用了下 house中相应的方法,没有什么逻辑,整理就不列举出来了。

运行结果:

地基打好啦!

框架搭好啦!

就只在控制台中打印出了这两个内容,也就是说应该是第一个线程执行完成之后,通知所有其他的线程,其他的线程中的一个符合要求的线程运行之后,剩下两个的线程并没有继续执行,是什么原因?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值