Java多线程WorkerThread模式

工作没来就一直等,工作来了就干活。

示例程序

  • Main 测试程序行为的类
  • ClientThread 表示发出工作请求的线程的类
  • Request 表示工作请求的类
  • Channel 收到工作请求并将工作请求交给工人线程的类
  • WorkerThread 表示工人线程的类

Main 类

public class Main {
  public static void main (String[] args) {
    Channel channel = new Channel(5);   //工人线程的个数
    channel.startWorkers();
    new ClientThread("Alice", channel).start();
    new ClientThread("Bobby", channel).start();
    new ClientThread("Chris", channel).start();
  }
}

ClientThread 类

import java.util.Random;

public class ClientThread extends Thread {
  private final Channel channel;
  private static final Random random = new Random();
  public ClientThread(String name, Channel channel){
    super( name);
    this.channel = channel;
  }
  public void run() {
    try {
      for (int i = 0; true; i++) {
        Request request = new Request(getName(), i);
        channel.putRequest(request);
        Thread.sleep(random.nextInt(1000));
      }
    } catch (InterruptException e) {}
  }
}

Request 类

import java.util.Random;

public class Request {
  private final String name;
  private final int number;
  private static final Random random = new Random();
  public Request(String name, int number){
    this.name = name;
    this.number = number;
  }
  public void execute() {
    System.out.println(Thread.currentThread().getName() + " executes " + this );
    try {
      Thread.sleep(random.nextInt(1000));
    } catch (InterruptedException e) {}
  }
  public String toString() {
    return "[ Request from " + name + " No. " + number + " ]";
  }
} 

Channel 类

public class Channel {
  private static final int MAX_REQUEST = 100;
  private final Request[]  requestQueue;
  private int tail ;    //下次putRequest的位置
  private int head;  //下次takeRequest的位置
  private int count ;  // Request 的数量 
  private final WorkerThread[]  threadPool;
  public Channel (int threads) {
    this.requestQueue = new Request[MAX_REQUEST];
    this.head = 0;
    this.tail = 0;
    this.count = 0;

    threadPool = new WorkerThread[threads];
    for (int i = 0; i < threadPool.length; i++){
      threadPool[i] = new WorkerThread("Worker-" + i , this);
    }
  }

  public void startWorkers() {
    for(int i = 0; i < threadPool.length; i++){
      threadPool[i].start();
    }
  }
  
  public synchronized void putRequest(Request request){
    while(count >= requestQueue.length){
      try {
        wait();
      } catch (InterruptedException e){}
      requestQueue[tail] = request;
      tail = (tail + 1) % requestQueue.length;
      count++;
      notifyAll();
    }
  }

  public synchronized Request takeRequest() {
    while (count <= 0) {
      try {
        wait();
      } catch (InterruptedException e) {}
      Request request = requestQueue[head];
      head = (head + 1) % requestQueue.length;
      count--;
      notifyAll();
      return request;
    }
  }
}

Worker Thread 类

public class WorkerThread extends Thread {
  private final Channel channel;
  public WorkerThread(String name, Channel channel){
    super(name);
    this.channel = channel;
  }
  public void run() {
    while (true) {
      Request request = channel.takeRequest();
      request.execute();
    }
  }
}

Worker Thread 模式中的登场角色

  • Client (委托者)
    Client 角色创建表示工作请求的Request角色,并将其传递给Channel角色。在示例程序中,由ClientThread类扮演此角色。
  • Channel (通讯线路)
    Channel角色接受来自Client角色的Rquest角色,并将其传递给Worker角色。在示例程序中,由Channel类扮演此角色。
  • Worker (工人)
    Worker角色从Channel角色中获取Request角色,并进行工作。当一项工作完成后,它会继续去获取另外的Request角色。在示例程序中,由WorkerThread类扮演此角色。
  • Request(请求)
    Request角色是表示工作的角色。Request角色中保存了进行工作所必需的信息。在示例程序中,由Request类扮演此角色。
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容