package com.example.design.master_worker;
import java.lang.Thread.State;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
public class Master {
/**
* 要做的事
*/
Queue<Work> works = new LinkedBlockingQueue<Work>();
/**
* 分配几个人来做相当于工人
*/
List<Thread> Workers = new ArrayList<Thread>();
/**
* 结果 key对应的事 value事的结果
*/
ArrayList<Object> results = new ArrayList<Object>();
public Master(int runCount, Worker worker) {
worker.setValue(works, results);
for (int i = 0; i <= runCount; i++) {
Workers.add(new Thread(worker));
}
}
public void submit(Work w) {
works.add(w);
}
public void execute() {
for (Thread run : Workers) {
run.start();
}
}
/**
* 判断线程是否全部终止
*
* @return true 有未完成
*/
public boolean checkIsComplete() {
for (Thread run : Workers) {
if ((run.getState() != State.TERMINATED)) {
return true;
}
}
return false;
}
}
package com.example.design.master_worker;
public abstract class Work {
Object obj;
public Work(Object obj) {
super();
this.obj = obj;
}
public abstract Object handler();
public Object getParm() {
return obj;
};
}
package com.example.design.master_worker;
import java.util.ArrayList;
import java.util.Map;
import java.util.Queue;
public class Worker implements Runnable {
Queue<Work> works;
ArrayList<Object> results;
public void setValue(Queue<Work> works, ArrayList<Object> results) {
this.works = works;
this.results = results;
}
@Override
public void run() {
while (true) {
Work work = works.poll();
if (work == null) {
break;
}
Object result = work.handler();
results.add(result);
}
}
}
package com.example.design.master_worker;
public class Work1 extends Work {
public Work1(Object obj) {
super(obj);
}
@Override
public Object handler() {
int i = (Integer) obj;
int t = i * i * i;
return t;
}
}
private static void masterTest(int t) {
Worker worker = new Worker();
Master master = new Master(5, worker);
for (int i = 0; i <= t; i++) {
master.submit(new Work1(i));
}
master.execute();
int result = 0;
ArrayList<Object> results = master.results;
while (results.size() > 0 || master.checkIsComplete()) {
if (results.size() > 0) {
result += (Integer) results.remove(0);
}
}
System.out.println(result);
}