赞
踩
突然翻到大学时敲的代码,记录下。
最近面试,遇到过。发现已经忘了怎么敲.
package com.li.Thread;
/**
*
* @author lijie
* @ClassName ThreadDemon
* @Description:
6.面包师傅与消费者问题
场景要求:
如果面包个数为10个, 面包师傅停止烤面包
如果面包个数为0个, 消费者排队等待
* @time 下午1:35:26
*/
public class ThreadDemon {
public static int numberBread = 10;
/**
*
* @author lijie
* @ClassName Master
* @Description: 制造面包
* @time 下午1:46:35
*/
class Master implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
while(true) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BreadBattle("生产者");
}
}
}
/**
*
* @author lijie
* @ClassName Bread
* @Description:消费面包
* @time 下午1:46:48
*/
class Bread implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
while(true) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BreadBattle("消费者");
}
}
}
public synchronized void BreadBattle(String type) {
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (type.equals("生产者")) {
if(numberBread<10) {
numberBread ++;
System.out.println("生产面包中"+Thread.currentThread().getName()+":"+numberBread);
}
else{
System.out.println("面包数超过10,暂停生产");
}
}
else {
if (numberBread>0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
numberBread --;
System.out.println("消费面包中"+Thread.currentThread().getName()+":"+numberBread);
} else {
System.out.println("等待面包生产中:"+numberBread);
}
}
}
public static void main(String[] args) {
ThreadDemon thread = new ThreadDemon();
ThreadDemon.Bread b = thread.new Bread();
ThreadDemon.Master m = thread.new Master();
Thread t1 = new Thread(b);
Thread t3 = new Thread(b);
Thread t4 = new Thread(b);
Thread t2 = new Thread(m);
Thread t5 = new Thread(m);
Thread t6 = new Thread(b);
Thread t7 = new Thread(b);
Thread t8 = new Thread(b);
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();
t7.start();
t8.start();
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。