Runnable
定义MyRunnable类实现Runnable接口。
实现run()方法,编写线程执行体。
创建线程对象,调用start()方法启动线程。
提示:推荐使用Runnable对象,因为Java单继承的局限性
参考代码
public class Demo03 implements Runnable {
@Override
public void run() {
for (int i
= 0; i
< 10; i
++) {
System
.out
.println("run方法");
}
}
public static void main(String
[] args
) {
Demo03 d3
= new Demo03();
new Thread(d3
).start();
for (int i
= 0; i
< 1000; i
++) {
System
.out
.println("Runnable接口");
}
}
}
实例(网图下载)
import org
.apache
.commons
.io
.FileUtils
;
import java
.io
.File
;
import java
.io
.IOException
;
import java
.net
.URL
;
public class Demo02 implements Runnable {
private String url
;
private String name
;
public Demo02(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
) {
Demo02 d1
= new Demo02("https://img-home.csdnimg.cn/images/20201001020546.jpg", "1.jpg");
Demo02 d2
= new Demo02("https://img-home.csdnimg.cn/images/20201001020546.jpg", "2.jpg");
Demo02 d3
= new Demo02("https://img-home.csdnimg.cn/images/20201001020546.jpg", "3.jpg");
new Thread(d1
).start();
new Thread(d2
).start();
new Thread(d3
).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异常,downloader方法出现问题");
}
}
}
总结
继承Thread类
子类继承Thread类具备多线程能力启动线程:子类对象.start()不建议使用:避免OOP单继承局限性
实现Runnable接口
实现接口Runnable具有多线程能力。启动线程:传入目标对象 + Thread对象.start()。推荐使用:避免单继承局限性,灵活方便,方便同一个对象被多个线程使用。
Demo demo
= new Demo();
new Thread(demo
, "***").start();
new Thread(demo
, "**").start();
new Thread(demo
, "*").start();