主题思想类似于流水线餐厅
模拟的request,可改成自己需要的类,添加自己需要的方法。
//请求对象
public class Request {
private final String name;
private final int number;
public Request(final String name, final int number) {
this.name = name;
this.number = number;
}
public void execute() {
System.out.println("工作"+Thread.currentThread().getName() + " 开始工作 " + this);
}
@Override
public String toString() {
return "请求号: " + number + " 请求者名字: " + name;
}
}
控制中心(流水线)
//流水线,控制中心。
public class Channel {
//接纳的最大 request 数量
private final static int MAX_REQUEST = 100;
//request 对象数组
private final Request[] requestQueue;
//request 数组头
private int head;
//request 数组尾
private int tail;
//统计 request 数量
private int count;
//工作线程数组
private final WorkerThread[] workerPool;
public Channel(int workers) {
//设置 request 数组
this.requestQueue = new Request[MAX_REQUEST];
this.head = 0;
this.tail = 0;
this.count = 0;
//开辟 n 个工作线程对象
this.workerPool = new WorkerThread[workers];
this.init();
}
//依次创建工作线程,并传递名字和 Channel 对象。
private void init() {
for (int i = 0; i < workerPool.length; i++) {
workerPool[i] = new WorkerThread("线程 " + i, this);
}
}
//启动已设好的工作线程。
public void startWorker() {
Arrays.asList(workerPool).forEach(WorkerThread::start);
}
//增添请求对象到请求数组中。
public synchronized void put(Request request) {
//当 request 数量大于设置的最大值,让当请求前线程wait()。
while (count >= requestQueue.length) {
try {
this.wait();
} catch (Exception e) {
}
}
System.out.println("请求线程开始请求");
//在数组末端加请求对象
this.requestQueue[tail] = request;
this.tail = (tail + 1) % requestQueue.length;
//request的统计加 --
this.count++;
this.notifyAll();
}
//处理请求
public synchronized Request take() {
//请求对象数组里没有请求时,就等等。
while (count <= 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("工作线程开始工作");
//拿出第一个请求
Request request = this.requestQueue[head];
this.head = (this.head + 1) % this.requestQueue.length;
//request 的统计减 --
this.count--;
this.notifyAll();
return request;
}
}
干活的线程(厨子)
//工作线程
public class WorkerThread extends Thread {
private final Channel channel;
public WorkerThread(String name, Channel channel) {
super(name);
System.out.println("创建线程对象: "+name);
this.channel = channel;
}
@Override
public void run() {
while (true) {
channel.take().execute();
}
}
}
请求的线程(顾客)
//请求线程
public class TransportThread extends Thread {
private final Channel channel;
//传递线程名字,和流水线对象。
public TransportThread(String name, Channel channel) {
super(name);
this.channel = channel;
}
@Override
public void run() {
try {
for (int i = 0; true; i++) {
Request request = new Request(getName(), i);
this.channel.put(request);
}
} catch (Exception e) {
}
}
}
Test_Main
public static void main(String[] args) {
//流水线对象, 设置工作线程数量。
final Channel channel = new Channel(8);
//请求线程
new TransportThread("黑黑", channel).start();
new TransportThread("红红", channel).start();
new TransportThread("花花", channel).start();
//启动工作线程
channel.startWorker();
}