多线程01
线程创建:
三种创建方式:
package com.thread.demo01; //创建线程方式一:继承Thread类,重写run()方法,用start开启线程 //总结:注意,线程开启不一定立即执行,由cpu调度执行 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线程 //创建线程对象 TestThread1 testThread1 = new TestThread1(); //调用start()方法,开启线程 testThread1.start(); for (int i = 0; i < 20; i++) { System.out.println("我在学习多线程---"+i); } } }
多线程实现图片下载
多线程下载需要下载器:
package com.thread.demo01; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; 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://t7.baidu.com/it/u=4198287529,2774471735&fm=193&f=GIF","1.jpg"); TestThread2 t2 = new TestThread2("https://t7.baidu.com/it/u=4198287529,2774471735&fm=193&f=GIF","2.jpg"); TestThread2 t3 = new TestThread2("https://t7.baidu.com/it/u=4198287529,2774471735&fm=193&f=GIF","3.jpg"); t1.start(); t2.start(); t3.start(); } } //下载器 class WebDownloader{ //下载方法 public void downloader(String url,String name){ try { FileUtils.copyURLToFile(new URL(url),new File(name)); } catch (IOException e) { System.out.println("IO异常,downloader方法出现异常"); throw new RuntimeException(e); } } }