Thread小练习(网图下载)

本练习需要使用的jar包为commons-io,如果你的项目是Java普通的项目的话需要去下载相应的jar包,若为Maven项目可以直接导入如下依赖

			 <!--版本应该无太大差异,可忽略-->
			<dependency>
            	<groupId>commons-io</groupId>
            	<artifactId>commons-io</artifactId>
            	<version>2.11.0</version>
        	</dependency>

代码部分:

package com.zzx.线程.Thread;

import org.apache.commons.io.FileUtils;

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

/**
 * @date: 2022/08/10/ 22:55
 * @author: ZhengZiXuan
 * @title: 练习Thread,实现一个多线程同步下载图片
 * @description:
 */
public class ThreadPractise extends Thread{

    //网络图片地址
    private String url;

    //保存的文件名
    private String name;

    @Override
    public void run() {
        WebDownloader webDownloader = new WebDownloader();
        webDownloader.downLoader(url,name);
        System.out.println("下载了文件名为:"+name);
    }

    public ThreadPractise(String url,String name) {
        this.name=name;
        this.url = url;
    }

    public static void main(String[] args) {
        ThreadPractise t1 = new ThreadPractise("https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2021%2F0731%2Fe91198a9j00qx35q30050c000j600nym.jpg&thumbnail=660x2147483647&quality=80&type=jpg","小姐姐1.jpg");
        ThreadPractise t2 = new ThreadPractise("https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2020%2F0308%2Faa2f8437j00q6uv1c001fc000hs00hsm.jpg&thumbnail=660x2147483647&quality=80&type=jpg","小姐姐2.jpg");
        ThreadPractise t3 = new ThreadPractise("https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2020%2F0308%2F94d8bda3j00q6uv1e000oc000hs00m7m.jpg&thumbnail=660x2147483647&quality=80&type=jpg","小姐姐3.jpg");
        //调用start方法,启动线程
        t1.start();
        t2.start();
        t3.start();

    }
}

//下载器
class WebDownloader{
    //下载方法
    public void downLoader(String pictureUrl, String name){
        try {
            FileUtils.copyURLToFile(new URL(pictureUrl),new File(name));
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("IO异常,downloader方法出现问题");
        }
    }
}

经过多次运行发现,调用start方法线程是同时执行的执行效果如下:

在这里插入图片描述
在这里插入图片描述
最后声明一下:下载好的图片默认在你的当前项目目录下

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Java多线程下载网络图片的实现方法如下: 1. 定义一个DownloadTask类,用于表示一个下载任务,其中包含下载的URL、存储路径和线程数等信息。 2. 在DownloadTask类中实现Runnable接口,并重写run()方法,在该方法中实现下载图片的逻辑,可以使用URLConnection或者HttpClient等工具类进行网络请求,并将下载的数据写入本地文件。 3. 在DownloadTask类中定义一个download()方法,用于启动下载任务,该方法将根据线程数划分下载任务,并启动多个线程进行下载。 4. 在应用程序主方法中创建DownloadTask对象,并调用download()方法启动下载任务。 下面是一个简单的Java多线程下载网络图片的示例代码: ```java import java.io.*; import java.net.*; import java.util.concurrent.*; public class DownloadTask implements Runnable { private String url; private String file; private int threadCount; public DownloadTask(String url, String file, int threadCount) { this.url = url; this.file = file; this.threadCount = threadCount; } public void run() { try { URLConnection conn = new URL(url).openConnection(); int contentLength = conn.getContentLength(); System.out.println("Total size: " + contentLength); RandomAccessFile raf = new RandomAccessFile(file, "rw"); raf.setLength(contentLength); ExecutorService executor = Executors.newFixedThreadPool(threadCount); for (int i = 0; i < threadCount; i++) { long start = (long) i * contentLength / threadCount; long end = (long) (i + 1) * contentLength / threadCount - 1; executor.execute(new DownloadThread(url, file, start, end)); } executor.shutdown(); executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MINUTES); System.out.println("Download completed."); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { String url = "http://www.example.com/image.jpg"; String file = "image.jpg"; int threadCount = 4; DownloadTask task = new DownloadTask(url, file, threadCount); task.download(); } } class DownloadThread implements Runnable { private String url; private String file; private long start; private long end; public DownloadThread(String url, String file, long start, long end) { this.url = url; this.file = file; this.start = start; this.end = end; } public void run() { try { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Range", "bytes=" + start + "-" + end); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); InputStream in = conn.getInputStream(); RandomAccessFile raf = new RandomAccessFile(file, "rw"); raf.seek(start); byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) != -1) { raf.write(buffer, 0, len); } raf.close(); in.close(); System.out.println("Part downloaded: " + start + "-" + end); } catch (Exception e) { e.printStackTrace(); } } } ``` 在上述代码中,DownloadTask类表示一个下载任务,其中包含下载的URL、存储路径和线程数等信息。在run()方法中实现下载图片的逻辑,将根据线程数划分下载任务,并启动多个线程进行下载。DownloadThread类表示一个下载线程,其中包含下载的URL、存储路径和下载的起始和结束位置等信息。在run()方法中实现下载数据的逻辑,使用HttpURLConnection发送请求,并将下载的数据写入本地文件。 在应用程序主方法中,创建DownloadTask对象,并调用download()方法启动下载任务。其中,url表示要下载的图片URL,file表示要保存的本地文件路径,threadCount表示下载线程数。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小郑要做干饭人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值