?? producerconsumerdemo.java
字號:
package com.david;
public class ProducerConsumerDemo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Box box = new Box();
Producer p = new Producer(box);
Consumer c = new Consumer(box);
new Thread(p).start();
new Thread(c).start();
}
}
class Bread{
private int id;
Bread(){}
Bread(int id){
this.id = id;
}
public String toString(){
return " "+id;
}
}
class Box{
private int index = 0;
Bread[] bread = new Bread[6];
public synchronized void put(Bread bd){
while(index == bread.length){
try {
wait();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
bread[index] = bd;
index++;
this.notify();
}
public synchronized Bread get(){
while(index == 0){
try {
wait();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
//bread[index] = bd;
index--;
this.notify();
return bread[index];
}
}
class Producer implements Runnable{
Box box;
Producer(Box box){
this.box = box;
}
public void run(){
for(int i = 0;i<20;i++){
Bread bd = new Bread(i);
box.put(bd);
System.out.println("the producer is producing bread:"+bd);
try {
Thread.sleep((int)(Math.random()*1000));
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable{
Box box;
Consumer(Box box){
this.box = box;
}
public void run(){
for(int i = 0;i<20;i++){
Bread bd = box.get();
System.out.println("the Consumer is consuming bread:"+bd);
try {
Thread.sleep((int)(Math.random()*1500));
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -