Skip to content

Instantly share code, notes, and snippets.

@zhugw
Created May 19, 2017 03:03
Show Gist options
  • Save zhugw/8c39cb000bf75cac973d8e4e49dfe0b7 to your computer and use it in GitHub Desktop.
Save zhugw/8c39cb000bf75cac973d8e4e49dfe0b7 to your computer and use it in GitHub Desktop.
TakeAppleForkJoin
package interview;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
/**
* 两个人轮流取苹果 每次只能取1/2/3 谁拿了最后一个谁就获胜
* 得到所有的取胜拿法
* Created by zhuguowei on 5/19/17.
*/
public class TakeAppleForkJoin extends RecursiveAction{
final int total = 25;
List<String> takeList ;
int count;
String takeResult;
public TakeAppleForkJoin(int count, String takeResult,List<String> takeList) {
this.count = count;
this.takeResult = takeResult;
this.takeList = takeList;
}
@Override
protected void compute() {
if(count > total){
return;
}
if(count == total){
if(takeResult.endsWith("1")) {
// System.out.printf("count: %d, takeResult: %s%n",count,takeResult);
takeList.add(takeResult.trim());
}
return;
}
invokeAll(new TakeAppleForkJoin(count+1,takeResult+" 1",takeList),
new TakeAppleForkJoin(count+2,takeResult+" 2",takeList),
new TakeAppleForkJoin(count+3,takeResult+" 3",takeList));
}
public static void main(String[] args) {
// final List<String> takeList = new CopyOnWriteArrayList<>();
long start = System.currentTimeMillis();
final List<String> takeList = Collections.synchronizedList(new ArrayList<>());
TakeAppleForkJoin takeAppleTask = new TakeAppleForkJoin(0,"",takeList);
ForkJoinPool pool = new ForkJoinPool();
pool.invoke(takeAppleTask);
long end = System.currentTimeMillis();
System.out.println(takeAppleTask.takeList.size());
System.out.printf("took time: %d%n", end-start);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment