📄 taskthread.java
字号:
package com.network.flashget;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.net.*;
import java.io.RandomAccessFile;
import java.io.Serializable;
class TaskThread extends Thread implements Serializable
{
//定义几个变量----------------------------------------------------------------------
public long finalStart = 0;
public long finalLength = 0;
public long startPosition = 0;
public long endPosition = 0;
public String fileName = null;
public String saveTo = null;
public URL url = null;
public boolean finishFlag = false;
public long downLength = 0;
transient public boolean stopFlag = false;
transient public boolean destroyFlag = false;
public void run()
{
int data = 0;
long totalLength = endPosition - startPosition;
BufferedInputStream bis = null;
RandomAccessFile randomFile = null;
System.out.println(startPosition);
System.out.println(endPosition);
System.out.println(totalLength);
try
{
File file = new File(saveTo);
//文件不存在则创建新文件--------------------------------------------------
if (!file.exists())
{
System.out.println("the same file is not exist");
file.createNewFile();
}
//创建随机读写文件--------------------------------------------------------
randomFile = new RandomAccessFile(file,"rw");
URLConnection urlConn = url.openConnection();
//移动读写指针------------------------------------------------------------
urlConn.setRequestProperty("RANGE", "bytes=" + startPosition+"-");
InputStream is = urlConn.getInputStream();
bis = new BufferedInputStream(is);
byte[] buf = new byte[1024];
//调整指针至写的位置------------------------------------------------------
randomFile.seek(startPosition);
outter:
while(downLength < finalLength && data!=-1)
{
//判断该是否暂停该线程-------------------------------------------------
try
{
sleep(500);
synchronized(this)
{
while(stopFlag)
{
if(destroyFlag)
{
break outter;
}
wait();
}
}
}
catch(InterruptedException e)
{
e.printStackTrace();
}
//若该线程的最后读写内容不到1024字节------------------------------------
if((finalLength - downLength) < 1023)
{
long len = finalLength - downLength + 1;
data = bis.read(buf,0,(int)len);
}
else
{
data = bis.read(buf);
}
randomFile.write(buf,0,data);
downLength = downLength + data;
startPosition = startPosition + data;
}
bis.close();
randomFile.close();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
bis.close();
randomFile.close();
System.out.println(startPosition);
System.out.println(downLength);
}
catch(Exception ie)
{
ie.printStackTrace();
}
}
}
//用于唤醒线程-------------------------------------------------
public synchronized void threadNotify()
{
stopFlag = false;
notify();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -