- package com.test;
- public class ThreadBox {
- private int content ;//产品
- private boolean has ;//标识盒子是否有东西
- public static void main(String[] args) {
- ThreadBox box =new ThreadBox();
- Thread pro =new Thread(new Product(box),"生产者");
- Thread cus =new Thread(new Custom(box),"消费者");
- pro.start();
- cus.start();
- }
- //生产好的添加到盒子里面
- public synchronized void setContent(int content) {
- if(has){
- try {
- wait();//盒子有东西就等待
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- has=true;
- notify();
- this.content = content;
- }
- public synchronized int getContent() {
- if(has==false){
- try {
- wait();//盒子没有东西等待
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- has=false;
- notify();//通知生产者,盒子没有东西了
- return content;
- }
- }
- class Product implements Runnable{
- private int content =1;
- ThreadBox box;
- public Product(ThreadBox box) {
- // TODO Auto-generated constructor stub
- this.box=box;
- }
- @Override
- public void run() {
- // TODO Auto-generated method stub
- while (true) {
- System.out.println("已生产的商品->"+content);
- box.setContent(content);
- try {
- Thread.sleep(200);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- content++;
- }
- }
- }
- class Custom implements Runnable{
- ThreadBox box;
- public Custom(ThreadBox box) {
- // TODO Auto-generated constructor stub
- this.box=box;
- }
- @Override
- public void run() {
- // TODO Auto-generated method stub
- while (true) {
- System.out.println("已消费的商品->"+box.getContent());
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }//end
- //输出结果
- 已生产的商品->1
- 已消费的商品->1
- 已生产的商品->2
- 已消费的商品->2
- 已生产的商品->3
- 已消费的商品->3
- 已生产的商品->4
- 已消费的商品->4
- //该片段来自于http://www.codesnippet.cn/detail/2007201513169.html
来源: http://www.codesnippet.cn/detail/2007201513169.html