10 多线程
创建多线程之方式一
package demo01;
//创建线程方式一:继承thread类,重写run方法,调用start开启线程
public class TestThread1 extends Thread{
@Override
public void run() {
//run方法线程体
for (int i = 0; i < 20; i++) {
System.out.println("我在看代码---"+i);
}
}
public static void main(String[] args) {
//main线程,主线程
//创建线程对象,开启线程
//线程开启不一定立即执行,由cpu调度
new TestThread1().start();
for (int i = 0; i < 200; i++) {
System.out.println("我在学习多线程**"+i);
}
}
}
多线程下载图片
package demo01;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
//练习Thread,实现多线程同步下载图片
public class TestThread2 extends Thread{
private String url;//网络图片地址
private String name;//保存的文件名
public TestThread2(String url, String name) {
this.url = url;
this.name = name;
}
@Override
public void run() {
WebDownloader webDownloader=new WebDownloader();
webDownloader.downloader(url,name);
System.out.println("下载文件名为"+name);
}
public static void main(String[] args) {
TestThread2 t1=new TestThread2("https://dss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=3472963130,1553781310&fm=55&app=54&f=JPEG?w=1140&h=640","1.png");
TestThread2 t2=new TestThread2("https://dss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=3472963130,1553781310&fm=55&app=54&f=JPEG?w=1140&h=640","2.png");
TestThread2 t3=new TestThread2("https://dss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=3472963130,1553781310&fm=55&app=54&f=JPEG?w=1140&h=640","3.png");
}
}
//下载器
class WebDownloader{
//下载方法
public void downloader(String url,String name){
try {
FileUtils.copyURLToFile(new URL(url),new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("IO异常,downloader方法出现问题");
}
}
}