|
|
此文章由 wangbo1118 原创或转贴,不代表本站立场和观点,版权归 oursteps.com.au 和作者 wangbo1118 所有!转贴必须注明作者、出处和本声明,并保持内容完整
第二题写了下,并没太大把握,大家有兴趣的可以讨论
import java.util.concurrent.ConcurrentLinkedQueue;
public class MyWorkItem implements WorkItem {
static ConcurrentLinkedQueue<Integer> queue = new ConcurrentLinkedQueue<Integer>();
WorkItemCompletionCallback callback = null;
// set tasks simply by integer
public MyWorkItem(int total) {
System.out.println( "constructing work items : " + total );
for(int i = 0;i < total;i++)
queue.add(i);
}
public int getItemCount(){
return queue.size();
}
@Override
public void execute(WorkItemCompletionCallback callback) {
synchronized (this) {
if(!queue.isEmpty())
System.out.println( "WorkItem is working on " + queue.poll());
else
callback.complete();
}
}
}
-----------------------------------------------------------------------------------------------
import java.util.concurrent.Callable;
public class WorkItemCallable implements Callable<String> {
WorkItem wi = null;
WorkItemCompletionCallback cb = null;
public WorkItemCallable(WorkItem w, WorkItemCompletionCallback c){
wi = w;
cb = c;
}
@Override
public String call() throws Exception {
wi.execute(cb);
return "OK";
}
}
-----------------------------------------------------------------------------------------------
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
public class MyWorkItemExecutor implements WorkItemExecutor, WorkItemCompletionCallback {
ExecutorService executorService = null;
public MyWorkItemExecutor(){
}
@Override
public void complete() {
executorService.shutdown();
}
@Override
public void executeWorkItem(WorkItem w, int parallelism) {
System.out.println( "Start working, threads : " + parallelism);
executorService = Executors.newFixedThreadPool(parallelism);
Future[] f = new Future[parallelism];
for(int i = 0;i < parallelism;i++){
f[i] = executorService.submit(new WorkItemCallable(w, this));
}
while(!executorService.isShutdown()){
try{
for(int i = 0;i < parallelism;i++){
if(!executorService.isShutdown() && f[i].isDone())
f[i] = executorService.submit(new WorkItemCallable(w, this));
else
break;
}
}catch(RejectedExecutionException reject){
// reject submit when tasks have already been finished
}
}
}
}
-----------------------------------------------------------------------------------------------
public class ExecutorTestMain {
public static void main(String[] args) {
WorkItemExecutor e = new MyWorkItemExecutor();
WorkItem wi = new MyWorkItem(100);
e.executeWorkItem(wi, 10);
}
}
|
|