⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 procust.java

📁 工厂--消费者模式,服务端代码.可用于监听客户端的请求并启动线程进行处理
💻 JAVA
字号:

import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: lizh
 * Date: 2006-8-26
 * Time: 17:08:47
 * To change this template use File | Settings | File Templates.
 */
public class ProCust {
  public ArrayList al = new ArrayList();
  public static void main(String[] args) {
    ProCust pc = new ProCust();
    pc.execute();
  }

  public void execute() {
    Producer pro = new Producer();
    pro.setArray(al);
    pro.start();
    Cust cust = new Cust();
    cust.setArray(al);
    cust.start();
  }
}

class Producer extends Thread {
  ArrayList al = null;

  public void setArray(ArrayList al) {
    this.al = al;
  }

  public void run() {
    int i = 0;
    int iSize = 0;
    int iCount = 0;
    while (true) {
      try {
        synchronized(al)
        {
          iSize = al.size();
          for(i = 0 ; iSize<5 && i<5-iSize ; i++)
          {
            al.add("Procuction");
            iCount ++;
            System.out.println("Produce iCount:"+iCount);
          }
        }
        synchronized(this)
        {
          notifyAll();
          sleep((long)(Math.random()*10)*100);
          //wait((long)(Math.random()*10)*1000);
        }
      }
      catch (Exception e) {
        System.out.println(e);
      }
    }
  }
}
class Cust extends Thread {
  ArrayList al = null;

  public void setArray(ArrayList al) {
    this.al = al;
  }

  public void run() {
    int i = 0;
    int iSize = 0;
    int iCount = 0;
    while (true) {
      try {
        synchronized(al)
        {
          iSize = al.size();
          for(i = 0 ;  i<iSize ; i++)
          {
            al.get(i);
            iCount ++;
            System.out.println("Cust iCount:"+iCount);
          }
          al.clear();
        }
        synchronized(this)
        {
          notifyAll();
          sleep((long)(Math.random()*10)*100);
          //wait((long)(Math.random()*10)*1000);
        }
      }
      catch (Exception e) {
        System.out.println(e);
      }
    }
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -