1、线程,进程,多线程
程序:指令和数据的有序集合,静态概念;
进程:操作系统分配资源的最小单元,程序的实例,程序执行的动态概念;
线程:CPU调度的最小单元,一个进程中至少有一个线程;
main()方法是主线程的入口,用来执行整个程序;
多线程的调度,由调度器完成,调度器与操作系统紧密相关,先后顺序不能人为干预;
对同一个资源存在资源竞争,需要加入并发控制;
线程调度会由额外的开销,如并发控制;
每个线程在自己工作内存交互,控制不当会造成数据不一致;
创建线程方式:
1、继承Thread类,重写run()方法,调用start开启线程;
2、开启线程后,不一定立刻执行,需要等待CPU的调度;
官网下载commons-io包
地址:https://commons.apache.org/proper/commons-io/download_io.cgi
commons-io 是一套io工具jar包;
IOUtils 包含一些工具类,用于处理读,写和拷贝,这些方法基于 InputStream, OutputStream, Reader 和 Writer工作;
FileUtils 包含一些工具类,它们基于File对象工作,包括读,写,拷贝和比较文件;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
//继承Thread类
public class TestThread1 extends Thread{
private String url;//图片地址
private String name;//保存文件名
//构造器
public TestThread1(String url,String name) {
this.url = url;
this.name = name;
}
//重写run方法
@Override
public void run(){
WebDownload webdownload = new WebDownload();
webdownload.download(url,name);
System.out.println("下载的文件名为:"+name);
}
public static void main(String[] args) {
TestThread1 thread1 = new TestThread1("https://img-home.csdnimg.cn/images/20220707025239.jpg","123.jpg");
TestThread1 thread2 = new TestThread1("https://img-home.csdnimg.cn/images/20220707025239.jpg","124.jpg");
TestThread1 thread3 = new TestThread1("https://img-home.csdnimg.cn/images/20220707025239.jpg","125.jpg");
thread1.start();
thread2.start();
thread3.start();
}
}
//下载图片类
class WebDownload{
public void download(String url,String filename){
try {
//下载图片并重命名
FileUtils.copyURLToFile(new URL(url),new File(filename));
} catch (IOException e) {
e.printStackTrace();
}
}
}
浙公网安备 33010602011771号