package com.kuangshen;
//创建线程方式一:继承Thread类,重写run()方法,调用start()开启线程
//总结:注意,线程开启不一定立即执行,由CPU调度执行
public class TestThread 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线程,主线程
//创建一个线程对象
TestThread testThread = new TestThread();
//调用star方法 开启线程
testThread.start();
for (int i = 0; i < 20; i++) {
System.out.println("我在学习多线程---"+i);
}
}
}
package com.kuangshen;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
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://www.kuangstudy.com//assert/course/c1/01.jpg","1.jpg");
TestThread2 t2 = new TestThread2("https://www.kuangstudy.com//assert/course/c1/02.jpg","2.jpg");
TestThread2 t3 = new TestThread2("https://www.kuangstudy.com//assert/course/c1/03.jpg","3.jpg");
//先下载t1
t1.start();
//然后是t2
t2.start();
//最后是t3
t3.start();
}
}
//下载器
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异常,download方法出现问题");
}
}
}
JAVA 复习-跟随狂神学JAVA-多线程复习01继承Thread
原文:https://www.cnblogs.com/deathpanda/p/14683504.html