多线程概要
1.线程流程图
2.线程实现的方法
(1)通过继承Thread方法,重写run()方法
示例代码
public class MainClass extends Thread{
public void run(){
for (int i = 0; i < 20; i++) {
System.out.println("我是另一个线程:"+i);
}
}
public static void main(String[] args) {
MainClass mainClass = new MainClass();
mainClass.start();
for (int i = 0; i < 20; i++) {
System.out.println("我是主线程:"+i);
}
}
}
多线程下载网络图片案例
package main;
//练习多线程同步下载图片
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class Thread2 extends Thread {
String url,name;
public Thread2(){}
public Thread2(String url,String name){
this.url=url;
this.name=name;
}
@Override
public void run() {
WebDwload webDwload = new WebDwload();
webDwload.dwonloader(url,name);
System.out.println("下载名:"+name);
}
public static void main(String[] args) {
Thread2 thread1 = new Thread2("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fgss0.baidu.com%2F-Po3dSag_xI4khGko9WTAnF6hhy%2Fzhidao%2Fpic%2Fitem%2F4034970a304e251fae75ad03a786c9177e3e534e.jpg&refer=http%3A%2F%2Fgss0.baidu.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1630031758&t=4f3f2155c04d7dd3c5690ed77bab29c0", "1.jpg");
Thread2 thread2 = new Thread2("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fgss0.baidu.com%2F-Po3dSag_xI4khGko9WTAnF6hhy%2Fzhidao%2Fpic%2Fitem%2F4034970a304e251fae75ad03a786c9177e3e534e.jpg&refer=http%3A%2F%2Fgss0.baidu.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1630031758&t=4f3f2155c04d7dd3c5690ed77bab29c0", "2.jpg");
Thread2 thread3 = new Thread2("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fgss0.baidu.com%2F-Po3dSag_xI4khGko9WTAnF6hhy%2Fzhidao%2Fpic%2Fitem%2F4034970a304e251fae75ad03a786c9177e3e534e.jpg&refer=http%3A%2F%2Fgss0.baidu.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1630031758&t=4f3f2155c04d7dd3c5690ed77bab29c0", "3.jpg");
thread1.start();thread2.start();thread3.start();
}
}
//下载器
class WebDwload{
public void dwonloader(String url,String name){
try {
FileUtils.copyURLToFile(new URL(url),new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("IO异常,WebDwload出错!");
}
}
}
(2)通过实现runnable来实现多线程
示例代码
package main;
//实现Runable,重写run()方法,执行线程需要丢入runnable实现接口类,调用start方法
public class Thread3 implements Runnable {
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("副线程:"+i);
}
}
public static void main(String[] args) {
// 创建Thred3
Thread3 thread3 = new Thread3();
// 创建线程,将实现runnable实现类开启线程
new Thread(thread3).start();
for (int i = 0; i < 20; i++) {
System.out.println("主线程:"+i);
}
}
}
小结
-
继承Thread类
子类继承父类具备多线程能力
启动线程:子类实例+.start()
注意:不建议使用为避免oop单继承的局限性
-
通过实现runnable
实现runnable具有多线程能力
启动线程:Thread(实现runnable类的实例).start()
注:推荐使用可避免单继承的局限性,方便同一个对象被多个线程使用