62,634
社区成员




void main(){
新建10个线程对象;
10个线程放入threadList;
for(Thread t in threadList){
t.start();
}
do{
if(list行数<MAX_LINE){
读取一行;
同步(list){
list.add(一行);
}
}else{
sleep(10);
}
}while(文件不空);
打印完成信息;
return;
}
ThreadClass extend Thread{
execute(){
同步(list){
if(list.size()>0){
取出一行;
}
}
if(成果取出一行){
计算该行数据;
同步(结果list){
结果list.add(该行的计算结果);
}
}else{
sleep(10);
}
}
}
原理基本如此,也可以使用java 8 parallel stream更加简单,需要复习下lambda,你也可以看一下。
import java.nio.channels.FileChannel;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.io.IOException;
public class MyJob implements Runnable{
public MyJob(FileChannel channel,long start,long end){
this.channel = channel;
this.start = start;
this.end = end;
try{
channel.position(start);
}catch(IOException e){
e.printStackTrace();
System.exit(1);
}
}
@Override
public void run(){
try{
while(channel.position() + bufSize < end){
buf = ByteBuffer.allocate(bufSize);
channel.read(buf);
buf.flip();
dates.add(buf);
}
buf = ByteBuffer.allocate((int)(end-channel.position()));
channel.read(buf);
buf.flip();
dates.add(buf);
finish = true;
System.out.println(Thread.currentThread().getName() + ":完成任务.");
}catch(IOException e){
e.printStackTrace();
System.exit(1);
}
}
public ArrayList<ByteBuffer> getDates(){
if(finish){
return dates;
}
return null;
}
private FileChannel channel = null;
private long start = 0L;
private long end = 0L;
private final int bufSize = 1024;
private ByteBuffer buf = null;
private ArrayList<ByteBuffer> dates = new ArrayList<>();
private boolean finish = false;
}
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.Path;
import static java.nio.file.StandardOpenOption.*;
import java.io.IOException;
public final class Test{
public static void main(String[] args){
String filePath = "source.bin";//设置数据源
Path path = Paths.get(filePath);
try(FileChannel channel = (FileChannel)(Files.newByteChannel(path,READ));){
//设置需要启动线程的数量.
int threadCount = 10;
Thread[] threads = new Thread[threadCount];
long start = 0L;
long end = 0L;
long contain = channel.size() / threadCount;
for(int i = 0 ; i < threadCount ; i ++){
start = end;
if(i != threadCount - 1){
end = end + contain;
}else{
end = channel.size();
}
threads[i] = new Thread(new MyJob(channel,start,end));
threads[i].setDaemon(false);//设置为用户线程
threads[i].start();
}
}catch(IOException e){
e.printStackTrace();
System.exit(1);
}
}
}