自己编了一个多线程下载程序,原理很简单,可是只有当线程为1时能成功,其它时程序的结果相当于仅有最后一个线程起作用。通过调试我知道应该是线程类出问题了,但不知怎么改,那位好心人帮我看看,谢谢。
public class Test3 {
private File fileIn=new File("D://logo.gif");
private File fileOut=new File("D://copy.gif");
//预先设定的线程数
private int ThreadNum=3;
public Test3() {
init();
}
private void init(){
try {
fileOut.createNewFile();
RandomAccessFile randIn=new RandomAccessFile(fileIn,"r");
RandomAccessFile randOut=new RandomAccessFile(fileOut,"rw");
randOut.setLength(randIn.length());
//block为每块的大小
long block=randIn.length()/ThreadNum;
for(int i=1;i<=ThreadNum;i++){
randIn.seek(block*(i-1));
randOut.seek(block*(i-1));
DownloadThread down=new DownloadThread (randIn,randOut,block);
down.setPriority(2);
down.start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String [] args){
Test3 app=new Test3();
}}
//线程类
public class DownloadThread extends Thread {
private RandomAccessFile randIn;
private RandomAccessFile randOut;
private long block;
public DownloadThread(RandomAccessFile in,RandomAccessFile out,long block){
randIn=in;
randOut=out;
this.block=block;
}
public void run(){
byte [] buffer=new byte[1024];
int offset=0;
long localSize=0;
try {
while ((offset = randIn.read(buffer)) != -1) {
if(localSize<=block){
randOut.write(buffer,0,offset);
localSize+=offset;
}
else{
System.out.println(localSize);
this.interrupt();
}
}
}
catch(Exception e){
System.err.println(e);
}
}
}
public class Test3 {
private File fileIn=new File("D://logo.gif");
private File fileOut=new File("D://copy.gif");
//预先设定的线程数
private int ThreadNum=3;
public Test3() {
init();
}
private void init(){
try {
fileOut.createNewFile();
RandomAccessFile randIn=new RandomAccessFile(fileIn,"r");
RandomAccessFile randOut=new RandomAccessFile(fileOut,"rw");
randOut.setLength(randIn.length());
//block为每块的大小
long block=randIn.length()/ThreadNum;
for(int i=1;i<=ThreadNum;i++){
randIn.seek(block*(i-1));
randOut.seek(block*(i-1));
DownloadThread down=new DownloadThread (randIn,randOut,block);
down.setPriority(2);
down.start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String [] args){
Test3 app=new Test3();
}}
//线程类
public class DownloadThread extends Thread {
private RandomAccessFile randIn;
private RandomAccessFile randOut;
private long block;
public DownloadThread(RandomAccessFile in,RandomAccessFile out,long block){
randIn=in;
randOut=out;
this.block=block;
}
public void run(){
byte [] buffer=new byte[1024];
int offset=0;
long localSize=0;
try {
while ((offset = randIn.read(buffer)) != -1) {
if(localSize<=block){
randOut.write(buffer,0,offset);
localSize+=offset;
}
else{
System.out.println(localSize);
this.interrupt();
}
}
}
catch(Exception e){
System.err.println(e);
}
}
}
RandomAccessFile randIn=new RandomAccessFile(fileIn,"r");
RandomAccessFile randOut=new RandomAccessFile(fileOut,"rw");
randOut.setLength(randIn.length());
//block为每块的大小
long block=randIn.length()/ThreadNum;
放到for循环底下就行了。
希望大家不要像我一样犯这种低级错误。