Fork/join
程序员文章站
2022-05-04 17:09:48
...
package com.example.test.thread;
import java.util.HashMap;
import java.util.concurrent.*;
public class TestHashMap {
public static void main(String[] args) throws ExecutionException, InterruptedException {
long start = System.currentTimeMillis();
ForkJoinPool forkJoinPool = (ForkJoinPool)Executors.newWorkStealingPool();
ThreadTest threadTest = new ThreadTest(10,"00000000",0,10);
forkJoinPool.submit(threadTest);
System.out.println(threadTest.get());
System.out.println((System.currentTimeMillis()-start)/1000);
}
}
class ThreadTest extends RecursiveTask{
private int count;
private String soutStr;
private int start;
private int end;
public ThreadTest(int count, String soutStr, int start, int end) {
this.count = count;
this.soutStr = soutStr;
this.start = start;
this.end = end;
}
@Override
protected String compute() {
int devi = start -end;
if(devi==0){
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
return soutStr;
}else{
int endTemp = (start+end)/2;
ThreadTest res = new ThreadTest(count, "222222222", start, start - endTemp);
res.fork();
ThreadTest res2 = new ThreadTest(count, "22222222222222", devi+1, end);
res2.fork();
String rs = res.join();
String rs2 = res.join();
return rs+rs2;
}
}
}