0%

多线程——继承Thread类

继承Thread类,重写run()方法,调用start并开启线程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.sympa.lesson01;

//创建线程方式一:继承Thread类,重写run()方法,调用start并开启线程
public class TestThread1 extends Thread{
@Override
public void run(){
//run方法线程体
for (int i = 0; i < 200; i++) {
System.out.println("我在看片\n" + i);
}
}
public static void main(String[] args){
//main线程,主线程

//创建一个线程对象
TestThread1 testThread1 = new TestThread1();

//调用start()方法开启线程
testThread1.start();
//线程开启不一定立即执行,由CPU调度执行
for (int i = 0; i < 200; i++) {
System.out.println("我在学习\n" + i);
}
}
}

练习Thread,实现多线程下载图片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package com.sympa.lesson01;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;

//练习Thread,实现多线程下载图片
public class TestThread02 extends Thread{
private String url;
private String name;
public TestThread02(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){
TestThread02 t1 = new TestThread02("https://sympawang.com/images/7%E7%A7%8Djoin.png", "01.jpg");
TestThread02 t2 = new TestThread02("https://sympawang.com/images/7%E7%A7%8Djoin.png", "02.jpg");
TestThread02 t3 = new TestThread02("https://sympawang.com/images/7%E7%A7%8Djoin.png", "03.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){
e.printStackTrace();
System.out.println("IO异常\n");
}
}
}
------ THEEND ------

欢迎关注我的其它发布渠道