继承Thread类
1、子类继承Thread类具备多线程能力
2、启动线程:子类对象.start()
3、不建议使用:避免oop单一继承局限性
public class TestThread1 extends Thread {
@Override
public void run() {
for (int i = 0; i < 200; i++) {
System.out.println("我在写代码~~~"+i);
}
}
public static void main(String[] args) {
TestThread1 testThread1 = new TestThread1();
testThread1.start();
for (int i = 0; i < 1000; i++) {
System.out.println("我在看学习视频~~~"+i);
}
}
}```
**实现Runnable接口**
1、实现接口Runnable具有多线程能力
2、启动线程:传入目标对象+Thread对象.start()
3、推荐使用:避免单一继承局限性,灵活方便,方便同一个对象被多个线程使用
```java
public class TestThread3 implements Runnable {
@Override
public void run() {
for (int i = 0; i < 200; i++) {
System.out.println("我在搞学习~~!");
}
}
public static void main(String[] args) {
TestThread3 testThread3 = new TestThread3();
Thread thread = new Thread(testThread3);
thread.start();
for (int i = 0; i < 1000; i++) {
System.out.println("我在写代码~~~~~~!");
}
}
}
从网页上面下载图片的代码,实现Runnable接口完成,代码如下
public class Thread2 implements Runnable {
private String url;//网络图片地址
private String name;//保存的文件名
public Thread2(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) {
Thread2 t1 = new Thread2("https://img2018.cnblogs.com/blog/1309478/201905/1309478-20190512183209781-282460662.png","1.jpg");
Thread2 t2 = new Thread2("https://img2018.cnblogs.com/blog/1309478/201905/1309478-20190512183435353-1154033226.png","2.jpg");
Thread2 t3 = new Thread2("https://img2018.cnblogs.com/blog/1309478/201905/1309478-20190512183346178-713966030.png","3.jpg");
//同时执行,不是按顺序下载
new Thread(t1).start();
new Thread(t2).start();
new Thread(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异常,downloader方法出现问题");
}
}
}



