import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.concurrent.Callable;
public class MyTask implements Callable<ByteBuffer> {
private long position;
private FileChannel inchannel;
public MyTask(FileChannel inchannel , long position) {
this.position = position;
this.inchannel = inchannel;
}
@Override
public ByteBuffer call() throws Exception {
ByteBuffer buffer = ByteBuffer.allocate(1024 * 8);
inchannel.read(buffer , position);
System.out.println(Thread.currentThread().getName() + "正在工作");
return buffer;
}
}
import org.junit.Test;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.concurrent.*;
import static java.util.concurrent.Executors.*;
public class TEST {
@Test
public void test1() throws Exception {
FileChannel inChannel = new RandomAccessFile("Z:\\勤奋蜂\\1.jpg", "r").getChannel();
FileChannel outChannel = new RandomAccessFile("Z:\\勤奋蜂\\2.jpg", "rw").getChannel();
try{
int threadCount = (int) (inChannel.size() / (1024 * 8));
if(inChannel.size() % (1024 * 8) != 0){
threadCount++;
}
System.out.println("线程总数:" + threadCount);
ByteBuffer[] buffers = new ByteBuffer[threadCount];
ExecutorService pool = newFixedThreadPool(threadCount);
for (int i = 0; i < threadCount; i++) {
Future<ByteBuffer> future = pool.submit(new MyTask(inChannel, i * 1024 * 8));
buffers[i] = future.get();
}
for (ByteBuffer buffer : buffers) {
buffer.flip();
outChannel.write(buffer);
}
pool.shutdown();
}finally {
inChannel.close();
outChannel.close();
}
}
}