⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 subtaskthread.java

📁 基于图形化的多线程下载器
💻 JAVA
字号:


import java.net.*;
import java.util.*;
import java.io.*;

/*
 * subTaskThread, if connection failed, loop until connect
 * if download finished, kill itself
 */
public class SubTaskThread extends Thread {
	private boolean debug = true;

	private TaskPortionInfo taskPortionInfo = null;
	private URL url = null;
	private RandomAccessFile dstFile = null;
	private boolean run = true;
	private boolean pause = false;

	public SubTaskThread(TaskPortionInfo taskPortion, URL url, File file) {

		this.taskPortionInfo = taskPortion;
		this.url = url;

		try {
			this.dstFile = new RandomAccessFile(file, "rw");
			// reset the dstFile position
			this.dstFile.seek(taskPortion.getNowPos());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void setRun(boolean run) {
		this.run = run;
	}

	public void setPause(boolean pause) {
		this.pause = pause;
	}

	public void run() {
		InputStream is = null;
		BufferedInputStream bis = null;
		try {
			is = getSubTaskThreadInputStream();
			// if subTaskThread connect failed, kill the thread
			if (is == null)
				return;
			bis = new BufferedInputStream(is);
			long count = 0;
			long startPos = taskPortionInfo.getNowPos();
			if (debug)
				System.out.println("subTaskThread " + this.getName()
						+ " is start!");
			MyUtil.sleepNow(1000);
			while (run) {
				// if(taskPortionInfo.getAcquiredPortionSize()<0)
				// System.out.println("error");
				checkPause();
				int m = 0;
				if ((m = bis.read()) != -1) {
					dstFile.write(m);
					taskPortionInfo.setNowPos(startPos + ++count);
				} else {
					break;
				}
			}
			if (debug)
				System.out.println("subTaskThread " + this.getName()
						+ " is died!");
		} catch (IOException e1) {
			e1.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				bis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}

	}

	private InputStream getSubTaskThreadInputStream() throws Exception {
		InputStream is = null;

		URLConnection conn = null;

		conn = url.openConnection();
		String endP = "bytes=" + taskPortionInfo.getNowPos() + "-"
				+ taskPortionInfo.getEndPos();
		conn.setRequestProperty("RANGE", endP);
		is = conn.getInputStream();
		return is;

	}

	private void checkPause() {
		synchronized (this) {
			while (pause) {
				if (debug)
					System.out.println("subTaskThread " + this.getName()
							+ " pause!");
				try {
					this.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		} // synchronized
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -