怎样实现多线程
案例:下载工具
一、DownLoadJFrame1.java
package util;import java.awt.Container;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.File;import java.io.InputStream;import java.io.RandomAccessFile;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JTextField;public class DownLoadJFrame1 extends JFrame implements ActionListener{// 声明组件private JLabel loadJLable;private JTextField loadJTextField;private JButton lodeJButton;//随机文件private RandomAccessFile accessFile;public DownLoadJFrame1() { //设置标题super("下载工具");//设置大小this.setSize(400,300); //设置居中this.setLocationRelativeTo(null);//关闭this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置可见性this.setVisible(true);//设置容器对象Container c=this.getContentPane();//设置容器面板c.setLayout(null);//实例化组件loadJLable=new JLabel("下载的地址");loadJTextField=new JTextField("http://localhost:8080/day31/image/ff.jpg");lodeJButton=new JButton("下载");//设置组件位置loadJLable.setBounds(10,20,80,30);loadJTextField.setBounds(90,20,280,30);lodeJButton.setBounds(120,100,100,30);//添加到面板c.add(loadJLable);c.add(loadJTextField);c.add(lodeJButton);//添加监听事件lodeJButton.addActionListener(this);}public static void main(String[] args) {new DownLoadJFrame1();}@Overridepublic void actionPerformed(ActionEvent e) { lodeJButton.setEnabled(false); //获取下载的路径 final String path=loadJTextField.getText(); try { //根据路径创建URL对象URL url=new URL(path);//打开连接HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection(); //设置请求方式httpURLConnection.setRequestMethod("GET");//设置连接的超时时间httpURLConnection.setConnectTimeout(5000);//设置请求的头信息httpURLConnection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.2; rv:21.0) Gecko/20100101 Firefox/21.0"); //获取下载的文件大小int size=httpURLConnection.getContentLength();//根据下载文件的名称 设置本地保存的文件File file=new File("E:"+path.substring(path.lastIndexOf("/")));//根据文件创建出对象accessFile=new RandomAccessFile(file, "rw");//设置大小accessFile.setLength(size);//释放资源accessFile.close();httpURLConnection.disconnect();//定义线程的数据量int threadNum=3;//往里边写数据for (int i = 1; i < threadNum; i++) {//计算出每个线程下载的平均量(大小)int blockSize=size/threadNum;//计算机每个线程的开始下载的位置final int startSize=(i-1)*blockSize;int temp=i*blockSize-1;if (i==threadNum) {if (temp<size) {temp=size;}}//计算出每个线程下载的结束位置final int endSize=temp;//文件随机读取的对象final RandomAccessFile threadFile=new RandomAccessFile(file,"rw");//创建线程new Thread(){public void run() {try {//根据路径创建URL对象URL url=new URL(path);//打开连接HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection(); //设置请求方式httpURLConnection.setRequestMethod("GET");//设置连接的超时时间httpURLConnection.setConnectTimeout(5000);//设置请求的头信息httpURLConnection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.2; rv:21.0) Gecko/20100101 Firefox/21.0"); System.out.println(Thread.currentThread().getName()+"从--"+startSize+"---开始下载,到"+endSize+"结束"); //设置读取的range的范围 httpURLConnection.setRequestProperty("Range","bytes="+startSize+"-"+endSize); //获取输入流对象 InputStream is=httpURLConnection.getInputStream(); //设置文件开始写入的位置 threadFile.seek(startSize); //缓冲区 byte buffer[]=new byte[1024]; //读取长度 int len=0; while((len=is.read(buffer))!=-1){ //写入 threadFile.write(buffer,0,len); } //释放资源 is.close(); threadFile.close(); httpURLConnection.disconnect(); } catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}};}.start();}//写文件 } catch (Exception e1) {// TODO Auto-generated catch blocke1.printStackTrace();}}}
DownLoadJFrames2.java
package util;import java.awt.Container;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.File;import java.io.RandomAccessFile;import java.net.HttpURLConnection;import java.net.URL;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JProgressBar;import javax.swing.JTextField;public class DownLoadJFrames2 extends JFrame {// 声明组件private JLabel downlodeJlable;private JTextField downlodeJTextField;private JButton downlodeJButton;private JLabel threadNumJable;private JTextField threadNumJTextField;private JProgressBar downlodeJProgressBar;public DownLoadJFrames2() {super("下载工具");// 设置大小this.setSize(400, 300);// 设置居中显示this.setLocationRelativeTo(null);// 设置窗体关闭即退出程序this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 可见性this.setVisible(true);// 获取容器对象Container c = this.getContentPane();// 设置容器面板布局为nullc.setLayout(null);// 实例化组件downlodeJlable = new JLabel("下载的地址");downlodeJTextField = new JTextField("http://localhost:8080/day31/image/ff.jpg");downlodeJButton = new JButton("下载");threadNumJable=new JLabel("开启线程数");threadNumJTextField=new JTextField("3");downlodeJProgressBar=new JProgressBar();// 设置组件的位置downlodeJlable.setBounds(10, 20, 80, 30);downlodeJTextField.setBounds(95, 20, 280, 30);threadNumJable.setBounds(10,60,80,30);threadNumJTextField.setBounds(95,60,280, 30);downlodeJProgressBar.setBounds(10,100,360, 10);downlodeJButton.setBounds(120, 120, 100, 30);// 添加到面板中c.add(downlodeJButton);c.add(downlodeJTextField);c.add(downlodeJlable);c.add(threadNumJTextField);c.add(threadNumJable);c.add(downlodeJProgressBar);// 添加点击事件downlodeJButton.addActionListener(new MyActionListener());}/** * 内部类 * * @param args */class MyActionListener implements ActionListener {// 随机文件private RandomAccessFile accessFile;@Overridepublic void actionPerformed(ActionEvent e) {downlodeJButton.setEnabled(false);// 获取下载的路径String path = downlodeJTextField.getText();String txThreadNun=threadNumJTextField.getText();try {// 根据路径创建URL对象URL url = new URL(path);// 打开连接HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();// 设置请求的方式httpURLConnection.setRequestMethod("GET");// 设置连接的超时时间httpURLConnection.setConnectTimeout(5000);// 设置请求的头信息httpURLConnection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.2; rv:21.0) Gecko/20100101 Firefox/21.0");//获取状态码int startusCode=httpURLConnection.getResponseCode();//是否响应成功的判断if (startusCode==200) {//获取下载的文件大小int size=httpURLConnection.getContentLength();//根据下载文件的名称 设置本地保存的文件File file=new File("E:"+path.substring(path.lastIndexOf("/")));//根据文件创建出RandomAccessFile对象accessFile=new RandomAccessFile(file,"rw"); //设置文件大小accessFile.setLength(size);//设置进度条大小downlodeJProgressBar.setMaximum(size);downlodeJProgressBar.setValue(0);accessFile.close();httpURLConnection.disconnect();//定义线程的数据量int threadNum=Integer.parseInt(txThreadNun);//往里边写数据for (int i = 1; i <=threadNum; i++) {//计算出每个线程下载的平均量(大小)int blockSize=size/threadNum;//计算出每个线程的开始下载的位置int startSize=(i-1)*blockSize;//计算出每个线程下载的结束位置 int endSize=i*blockSize-1; if (i==threadNum) {if (endSize<size) {endSize=size;}} //文件随机读取的对象 RandomAccessFile threadFile=new RandomAccessFile(file, "rw"); new DownLodeThread(path, startSize, endSize, threadFile, downlodeJProgressBar).start(); //写文件}}} catch (Exception e1) {// TODO Auto-generated catch blocke1.printStackTrace();}}}public static void main(String[] args) {new DownLoadJFrames2();}}
工具包DownLodeThread.java
package util;import java.io.InputStream;import java.io.RandomAccessFile;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;public class DownLodeThread extends Thread {// 下载的路径private String path;// 开始位置private int startSize;// 结束位置private int endSize;// 随机读取文件的对象private RandomAccessFile threadFile;// 实例化public DownLodeThread(String path, int startSize, int endSize,RandomAccessFile threadFile) {super();this.path = path;this.startSize = startSize;this.endSize = endSize;this.threadFile = threadFile;}@Overridepublic void run() {try {// 根据路径创建URL对象URL url = new URL(path);// 打开连接HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();// 设置请求的方式httpURLConnection.setRequestMethod("GET");// 设置连接的超时时间httpURLConnection.setConnectTimeout(5000);// 设置请求的头信息httpURLConnection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.2; rv:21.0) Gecko/20100101 Firefox/21.0");System.out.println(Thread.currentThread().getName() + "从--"+ startSize + "---开始下载,到" + endSize + "结束");// 设置你读取的range的范围httpURLConnection.setRequestProperty("Range", "bytes=" + startSize+ "-" + endSize);// 获取输入流对象InputStream is = httpURLConnection.getInputStream();// 设置文件开始写入的位置threadFile.seek(startSize);// 缓冲区byte buffer[] = new byte[1024];// 读取的长度int len = 0;// 读取while ((len = is.read(buffer)) != -1) {// 写入threadFile.write(buffer, 0, len);}// 释放资源is.close();threadFile.close();httpURLConnection.disconnect();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
二、怎样查询AVI("video/x-msvideo")的类型
用枚举类FileType.java
package util;/** * 枚举 * @author yanmei * */public enum FileType {/** * type <mime-mapping> <extension>avi</extension> * <mime-type>video/x-msvideo</mime-type> </mime-mapping> */AVI("video/x-msvideo");private String value;private FileType(String value){this.value=value;}public String getValue(){return value;}public static FileType FindByValue(String value){FileType fileType=null;FileType types[]=FileType.values();for(FileType type:types){if (type.getValue().equals(value)) {fileType=type;break;}}return fileType;}}
测试类FileTest.java
package util;import static org.junit.Assert.*;import org.junit.Test;public class FileTest {@Testpublic void test() {FileType fileType=FileType.FindByValue("video/x-msvideo");System.out.println(fileType.name());}}