package org.jeecg.modules.ddp.controller.ddpReport;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
/**
* User: Administrator
* Date: 2022/1/19/019
* Time: 9:50
* Description:
*/
public class threadTest implements Runnable{
//自定义线程类实现Runnable接口
//从写run方法,编写线程执行体
//创建线程对象,调用start()方法启动线程
@Override
public void run(){
for (int i = 0; i < 200; i++) {
System.out.println("我在看代码");
}
}
//打印台上两个程序是交替执行的
public static void main(String[] args) {
threadTest threadTest = new threadTest();
Thread thread = new Thread(threadTest);
thread.start();
//new Thread(threadTest).start();
for (int i = 0; i < 1000; i++) {
System.out.println("我在写程序");
}
}
}
巩固 Runnable 练习
package org.jeecg.modules.ddp.controller.ddpReport;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
/**
* User: Administrator
* Date: 2022/1/19/019
* Time: 9:50
* Description:
*/
public class threadTest implements Runnable{
/**
* 地址
*/
private String url;
/**
* 保存文件名
*/
private String name;
public threadTest(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) {
threadTest threadTest1 = new threadTest("https://t7.baidu.com/it/u=4036010509,3445021118&fm=193&f=GIF","图片1.jpg");
threadTest threadTest2 = new threadTest("https://t7.baidu.com/it/u=963301259,1982396977&fm=193&f=GIF","图片2.jpg");
threadTest threadTest3 = new threadTest("https://t7.baidu.com/it/u=1575628574,1150213623&fm=193&f=GIF","图片3.jpg");
new Thread(threadTest1).start();
new Thread(threadTest2).start();
new Thread(threadTest3).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出现问题");
}
}
}
}
建议使用Runnable
实现Runnable接口比继承Thread类所具有的优势:
1):适合多个相同的程序代码的线程去处理同一个资源
2):可以避免java中的单继承的限制
3):增加程序的健壮性,代码可以被多个线程共享,代码和数据独立