放苹果 java_用Java代码模拟实现:一个人不断往箱子里放苹果,另一个人不断从箱子里取苹果,箱子里只能放5个苹...

展开全部

package com.zt.test;

import java.util.Stack;

public class Test7 {

private Stack box;

public String operationBox(boolean flag, String num) {

32313133353236313431303231363533e58685e5aeb931333337383833String str = "";

synchronized (Test7.class) {

if (flag) {

this.box.push(num);

} else {

str = this.box.pop();

}

}

return str;

}

public static void main(String args[]) {

Test7 a = new Test7();

a.initApples();

}

public Test7() {

this.box = new Stack();

}

public void forSleep(int i) {

try {

Thread.sleep(i);

} catch (Exception e) {

e.printStackTrace();

}

}

/**

* 放苹果的人

*/

public void putApple() {

int no = 1;

while (true) {

this.forSleep(1000);

int check = this.box.size();

System.out.println("---------现在有" + check + "个苹果---------");

if (check >= 5) {

System.out.println("------------箱子里有5个苹果无法放入------------");

continue;

} else {

System.out

.println("------------放入第" + no + "个苹果--------------");

this.operationBox(true, no + "");

no = no + 1;

}

}

}

/**

* 拿苹果的人

*/

public void getApple() {

while (true) {

this.forSleep(800);

int check = this.box.size();

System.out.println("=========现在有" + check + "个苹果============");

if (check == 0) {

System.out.println("==========箱子里有0个苹果无法去除===========");

continue;

} else {

String str = this.operationBox(false, null);

System.out.println("==========从箱子出取出第" + str + "个苹果==========");

}

}

}

/*

* 初始化两个人

*/

public void initApples() {

Thread t1 = new Thread(new Runnable() {

public void run() {

try {

putApple();

} catch (Exception e) {

}

}

});

t1.start();

Thread t2 = new Thread(new Runnable() {

public void run() {

try {

getApple();

} catch (Exception e) {

}

}

});

t2.start();

}

}

一个放一个拿,operationBox()锁住stack的操作,forsleep方法是进行休眠的,模拟一块一慢,如果需要无序时间,自己写随机函数进行线程休眠。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值