java 通过继承Thread类实现多线程很多简单:
只需要重写run方法即可。
比如我们分三个线程去京东下载三张图片:
1、先写个下载类:
注意导入CommonsIO 包
public class WebDownLoad {
public void download(String url, String name) {
try {
FileUtils.copyURLToFile(new URL(url), new File(name));
} catch (MalformedURLException e) {
e.printStackTrace();
System.out.println("url 不合法");
} catch (IOException e) {
e.printStackTrace();
System.out.println("图片下载失败");
}
}
}
2、编写线程类在run()方法中执行下载操作:
class TDdownload extends Thread{
private String url; // 远程路径
private String name; // 存储路劲
public TDdownload(String url, String name) {
this.name = name;
this.url = url;
}
@Override
public void run() {
WebDownLoad wd = new WebDownLoad();
wd.download(url, name);
System.out.println(name);
}
3、调用start() 方法启动线程
public static void main(String[] args) {
TDdownload td1 = new TDdownload("http://img11.360buyimg.com/n1/s450x450_jfs/t1/95372/26/10103/109107/5e181892Eb698a3bc/2033bb2f00c38f93.jpg", "电脑.jpg");
TDdownload td2 = new TDdownload("http://img14.360buyimg.com/n1/s450x450_jfs/t1/106229/22/9051/174570/5e0d4a59E099ec5cd/2501bf3e7f96c1fb.jpg", "键盘.jpg");
TDdownload td3 = new TDdownload("http://img13.360buyimg.com/n1/s450x450_jfs/t1/5916/10/5128/160256/5b9f0e9bEbc9f4db4/14f062751af6ce26.jpg", "鼠标.jpg");
// 启动多线程
td1.start();
td2.start();
td3.start();
}