java 多執行緒 master worker模式

心鑫發表於2013-11-01
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);
	}


相關文章