package design.demo;
import java.util.function.Consumer;
/**
* @author:ace
* @date:2020-01-07
*/
public class MySpliterator<T> {
T[] table;
int index;
int fence;
public MySpliterator(T[] table,int origin,int fence){
this.table = table;
this.index = origin;
this.fence = fence;
}
private int getFence(){
if(fence < 0){
fence = table.length;
}
return fence;
}
public MySpliterator<T> trySplit(){
int hi = getFence();
int lo = index;
int mid = (lo + hi) >>> 1;
if(lo >= mid){
return null;
}
return new MySpliterator<>(table,lo,index=mid);
}
public void forEach(Consumer<? super T> action){
int i,hi;
if((hi=fence) < 0){
hi = fence = table.length;
}
if(table.length>=hi && (i=index)>=0 && (i< (index = hi)) ){
do{
System.out.printf("current index : " + index + " | ");
action.accept(table[i++]);
}while(i<hi);
}
}
public static void main(String[] args) {
String[] strings = new String[16];
for (int i = 0; i < 16; i++) {
strings[i] = "string" + i;
}
MySpliterator<String> spliterator = new MySpliterator<>(strings,0,-1);
int index = 1;
do{
new Thread(new MyRunnable(spliterator,"thread"+ index++)).start();
}while((spliterator = spliterator.trySplit())!=null);
}
static class MyRunnable implements Runnable{
MySpliterator<String> spliterator;
String name;
public MyRunnable(MySpliterator<String> spliterator,String name){
this.spliterator = spliterator;
this.name = name;
}
@Override
public void run() {
spliterator.forEach(item->{
System.out.println(name + " : " + item);
});
}
}
}
网友评论