android多线程下载2

简介: <p>在上一集中,我们简单介绍了如何创建多任务下载,但那种还不能拿来实用,这一集我们重点通过代码为大家展示如何创建多线程断点续传下载,这在实际项目中很常用.</p> <p>main.xml:</p> <div class="dp-highlighter bg_html"> <div class="bar"> <div class="tools"><strong>[html]</s

在上一集中,我们简单介绍了如何创建多任务下载,但那种还不能拿来实用,这一集我们重点通过代码为大家展示如何创建多线程断点续传下载,这在实际项目中很常用.

main.xml:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="fill_parent"  
  6.     >  
  7.     <EditText  
  8.         android:layout_width="match_parent"  
  9.         android:layout_height="wrap_content"  
  10.         android:id="@+id/editText"  
  11.         android:text="http://gongxue.cn/yingyinkuaiche/UploadFiles_9323/201008/2010082909434077.mp3"  
  12.     />  
  13.     <LinearLayout  
  14.         android:orientation="horizontal"  
  15.         android:layout_width="match_parent"  
  16.         android:layout_height="wrap_content"  
  17.     >  
  18.         <Button  
  19.             android:layout_width="wrap_content"  
  20.             android:layout_height="wrap_content"  
  21.             android:id="@+id/downButton"  
  22.             android:text="Download"  
  23.         />  
  24.         <Button  
  25.             android:layout_width="wrap_content"  
  26.             android:layout_height="wrap_content"  
  27.             android:id="@+id/pauseButton"  
  28.             android:enabled="false"  
  29.             android:text="Pause"  
  30.         />  
  31.     </LinearLayout>  
  32.       
  33.     <ProgressBar  
  34.         android:layout_width="match_parent"  
  35.         android:layout_height="18dp"  
  36.         style="?android:attr/progressBarStyleHorizontal"  
  37.         android:id="@+id/progressBar"  
  38.     />  
  39.     <TextView  
  40.         android:layout_width="fill_parent"  
  41.         android:layout_height="wrap_content"  
  42.         android:id="@+id/textView"  
  43.         android:gravity="center"  
  44.     />  
  45. </LinearLayout>  

 

String.xml:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <string name="hello">Hello World, Main!</string>  
  4.     <string name="app_name">多线程断点续传下载</string>  
  5. </resources>  


AndroidManifest.xml:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.       package="sms.multithreaddownload"  
  4.       android:versionCode="1"  
  5.       android:versionName="1.0">  
  6.     <application android:icon="@drawable/icon" android:label="@string/app_name">  
  7.         <activity android:name=".Main"  
  8.                   android:label="@string/app_name">  
  9.             <intent-filter>  
  10.                 <action android:name="android.intent.action.MAIN" />  
  11.                 <category android:name="android.intent.category.LAUNCHER" />  
  12.             </intent-filter>  
  13.         </activity>  
  14.      <uses-library android:name="android.test.runner" />  
  15.     </application>  
  16.     <uses-sdk android:minSdkVersion="8" />  
  17.     <instrumentation  
  18.         android:targetPackage="sms.multithreaddownload"  
  19.         android:name="android.test.InstrumentationTestRunner" />  
  20.     <!-- 访问网络的权限 -->  
  21.     <uses-permission android:name="android.permission.INTERNET"/>  
  22.     <!-- SDCard写数据的权限 -->  
  23.     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  
  24.       
  25.   
  26. </manifest>   

 

activity程序:

  1. package sms.multithreaddownload;  
  2.   
  3. import java.io.File;  
  4.   
  5. import sms.multithreaddownload.bean.DownloadListener;  
  6. import sms.multithreaddownload.service.DownloadService;  
  7. import android.app.Activity;  
  8. import android.os.Bundle;  
  9. import android.os.Environment;  
  10. import android.os.Handler;  
  11. import android.os.Message;  
  12. import android.view.View;  
  13. import android.view.View.OnClickListener;  
  14. import android.widget.Button;  
  15. import android.widget.EditText;  
  16. import android.widget.ProgressBar;  
  17. import android.widget.TextView;  
  18. import android.widget.Toast;  
  19.   
  20. public class Main extends Activity {  
  21.     private EditText path;  
  22.     private TextView progress;  
  23.     private ProgressBar progressBar;  
  24.     private Handler handler = new UIHandler();  
  25.     private DownloadService servcie;  
  26.     private Button downButton;  
  27.     private Button pauseButton;  
  28.   
  29.     private final class UIHandler extends Handler {  
  30.         @Override  
  31.         public void handleMessage(Message msg) {  
  32.             switch (msg.what) {  
  33.                 case 1:  
  34.                     int downloaded_size = msg.getData().getInt("size");  
  35.                     progressBar.setProgress(downloaded_size);  
  36.                     int result = (int) ((float) downloaded_size / progressBar.getMax() * 100);  
  37.                     progress.setText(result + "%");  
  38.                     if (progressBar.getMax() == progressBar.getProgress()) {  
  39.                         Toast.makeText(getApplicationContext(), "下载完成", Toast.LENGTH_LONG).show();  
  40.                     }  
  41.             }  
  42.         }  
  43.     }  
  44.   
  45.     @Override  
  46.     public void onCreate(Bundle savedInstanceState) {  
  47.         super.onCreate(savedInstanceState);  
  48.         setContentView(R.layout.main);  
  49.         path = (EditText) this.findViewById(R.id.editText);  
  50.         progress = (TextView) this.findViewById(R.id.textView);  
  51.         progressBar = (ProgressBar) this.findViewById(R.id.progressBar);  
  52.         downButton = (Button) this.findViewById(R.id.downButton);  
  53.         pauseButton = (Button) this.findViewById(R.id.pauseButton);  
  54.         downButton.setOnClickListener(new DownloadButton());  
  55.         pauseButton.setOnClickListener(new PauseButton());  
  56.     }  
  57.   
  58.     private final class DownloadButton implements View.OnClickListener {  
  59.         @Override  
  60.         public void onClick(View v) {  
  61.             DownloadTask task;  
  62.             try {  
  63.                 task = new DownloadTask(path.getText().toString());  
  64.                 servcie.isPause = false;  
  65.                 v.setEnabled(false);  
  66.                 pauseButton.setEnabled(true);  
  67.                 new Thread(task).start();  
  68.             } catch (Exception e) {  
  69.                 e.printStackTrace();  
  70.             }  
  71.         }  
  72.     }  
  73.   
  74.     public class PauseButton implements OnClickListener {  
  75.         @Override  
  76.         public void onClick(View v) {  
  77.             servcie.isPause = true;  
  78.             v.setEnabled(false);  
  79.             downButton.setEnabled(true);  
  80.         }  
  81.     }  
  82.   
  83.     public void pause(View v) {  
  84.     }  
  85.   
  86.     private final class DownloadTask implements Runnable {  
  87.   
  88.         public DownloadTask(String target) throws Exception {  
  89.             if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {  
  90.                 File destination = Environment.getExternalStorageDirectory();  
  91.                 servcie = new DownloadService(target, destination, 3, getApplicationContext());  
  92.                 progressBar.setMax(servcie.fileSize);  
  93.             } else {  
  94.                 Toast.makeText(getApplicationContext(), "SD卡不存在或写保护!", Toast.LENGTH_LONG).show();  
  95.             }  
  96.         }  
  97.   
  98.         @Override  
  99.         public void run() {  
  100.             try {  
  101.                 servcie.download(new DownloadListener() {  
  102.   
  103.                     @Override  
  104.                     public void onDownload(int downloaded_size) {  
  105.                         Message message = new Message();  
  106.                         message.what = 1;  
  107.                         message.getData().putInt("size", downloaded_size);  
  108.                         handler.sendMessage(message);  
  109.                     }  
  110.   
  111.                 });  
  112.             } catch (Exception e) {  
  113.                 e.printStackTrace();  
  114.             }  
  115.   
  116.         }  
  117.     }  
  118. }  


工具类:

  1. package sms.multithreaddownload.bean;  
  2.   
  3. import android.content.Context;  
  4. import android.database.sqlite.SQLiteDatabase;  
  5. import android.database.sqlite.SQLiteOpenHelper;  
  6.   
  7. public class DBHelper extends SQLiteOpenHelper {  
  8.   
  9.     public DBHelper(Context context) {  
  10.         super(context, "MultiDownLoad.db"null1);  
  11.     }  
  12.   
  13.     @Override  
  14.     public void onCreate(SQLiteDatabase db) {  
  15.         db.execSQL("CREATE TABLE fileDownloading(_id integer primary key autoincrement,downPath varchar(100),threadId INTEGER,downLength INTEGER)");  
  16.     }  
  17.   
  18.     @Override  
  19.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
  20.         // TODO Auto-generated method stub  
  21.   
  22.     }  
  23.   
  24. }  


 

  1. package sms.multithreaddownload.bean;  
  2.   
  3. public interface DownloadListener {  
  4.     public void onDownload(int downloaded_size);  
  5. }  


 

  1. package sms.multithreaddownload.bean;  
  2.   
  3. import java.io.File;  
  4. import java.io.InputStream;  
  5. import java.io.RandomAccessFile;  
  6. import java.net.HttpURLConnection;  
  7. import java.net.URL;  
  8.   
  9. import sms.multithreaddownload.service.DownloadService;  
  10.   
  11. import android.util.Log;  
  12.   
  13. public final class MultiThreadDownload implements Runnable {  
  14.     public int id;  
  15.     private RandomAccessFile savedFile;  
  16.     private String path;  
  17.     /* 当前已下载量 */  
  18.     public int currentDownloadSize = 0;  
  19.     /* 下载状态 */  
  20.     public boolean finished;  
  21.     /* 用于监视下载状态 */  
  22.     private final DownloadService downloadService;  
  23.     /* 线程下载任务的起始点 */  
  24.     public int start;  
  25.     /* 线程下载任务的结束点 */  
  26.     private int end;  
  27.   
  28.     public MultiThreadDownload(int id, File savedFile, int block, String path, Integer downlength, DownloadService downloadService) throws Exception {  
  29.         this.id = id;  
  30.         this.path = path;  
  31.         if (downlength != nullthis.currentDownloadSize = downlength;  
  32.         this.savedFile = new RandomAccessFile(savedFile, "rwd");  
  33.         this.downloadService = downloadService;  
  34.         start = id * block + currentDownloadSize;  
  35.         end = (id + 1) * block;  
  36.     }  
  37.   
  38.     @Override  
  39.     public void run() {  
  40.         try {  
  41.             HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();  
  42.             conn.setConnectTimeout(5000);  
  43.             conn.setRequestMethod("GET");  
  44.             conn.setRequestProperty("Range""bytes=" + start + "-" + end); // 设置获取数据的范围  
  45.   
  46.             InputStream in = conn.getInputStream();  
  47.             byte[] buffer = new byte[1024];  
  48.             int len = 0;  
  49.             savedFile.seek(start);  
  50.             while (!downloadService.isPause && (len = in.read(buffer)) != -1) {  
  51.                 savedFile.write(buffer, 0, len);  
  52.                 currentDownloadSize += len;  
  53.             }  
  54.             savedFile.close();  
  55.             in.close();  
  56.             conn.disconnect();  
  57.             if (!downloadService.isPause) Log.i(DownloadService.TAG, "Thread " + (this.id + 1) + "finished");  
  58.             finished = true;  
  59.         } catch (Exception e) {  
  60.             e.printStackTrace();  
  61.             throw new RuntimeException("File downloading error!");  
  62.         }  
  63.     }  
  64. }  


service类:

  1. package sms.multithreaddownload.service;  
  2.   
  3. import java.io.File;  
  4. import java.io.RandomAccessFile;  
  5. import java.net.HttpURLConnection;  
  6. import java.net.URL;  
  7. import java.util.HashMap;  
  8. import java.util.List;  
  9. import java.util.Map;  
  10. import java.util.Map.Entry;  
  11. import java.util.UUID;  
  12. import java.util.concurrent.ConcurrentHashMap;  
  13. import java.util.regex.Matcher;  
  14. import java.util.regex.Pattern;  
  15.   
  16. import sms.multithreaddownload.bean.DBHelper;  
  17. import sms.multithreaddownload.bean.DownloadListener;  
  18. import sms.multithreaddownload.bean.MultiThreadDownload;  
  19.   
  20. import android.content.Context;  
  21. import android.database.Cursor;  
  22. import android.database.sqlite.SQLiteDatabase;  
  23.   
  24.   
  25. public class DownloadService {  
  26.     public static final String TAG = "tag";  
  27.     /* 用于查询数据库 */  
  28.     private DBHelper dbHelper;  
  29.     /* 要下载的文件大小 */  
  30.     public int fileSize;  
  31.     /* 每条线程需要下载的数据量 */  
  32.     private int block;  
  33.     /* 保存文件地目录 */  
  34.     private File savedFile;  
  35.     /* 下载地址 */  
  36.     private String path;  
  37.     /* 是否停止下载 */  
  38.     public boolean isPause;  
  39.     /* 线程数 */  
  40.     private MultiThreadDownload[] threads;  
  41.     /* 各线程已经下载的数据量 */  
  42.     private Map<Integer, Integer> downloadedLength = new ConcurrentHashMap<Integer, Integer>();  
  43.   
  44.     public DownloadService(String target, File destination, int thread_size, Context context) throws Exception {  
  45.         dbHelper = new DBHelper(context);  
  46.         this.threads = new MultiThreadDownload[thread_size];  
  47.         this.path = target;  
  48.         URL url = new URL(target);  
  49.         HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  50.         conn.setConnectTimeout(5000);  
  51.         conn.setRequestMethod("GET");  
  52.   
  53.         if (conn.getResponseCode() != 200) {  
  54.             throw new RuntimeException("server no response!");  
  55.         }  
  56.   
  57.         fileSize = conn.getContentLength();  
  58.         if (fileSize <= 0) {  
  59.             throw new RuntimeException("file is incorrect!");  
  60.         }  
  61.         String fileName = getFileName(conn);  
  62.         if (!destination.exists()) destination.mkdirs();  
  63.         // 构建一个同样大小的文件  
  64.         this.savedFile = new File(destination, fileName);  
  65.         RandomAccessFile doOut = new RandomAccessFile(savedFile, "rwd");  
  66.         doOut.setLength(fileSize);  
  67.         doOut.close();  
  68.         conn.disconnect();  
  69.   
  70.         // 计算每条线程需要下载的数据长度  
  71.         this.block = fileSize % thread_size == 0 ? fileSize / thread_size : fileSize / thread_size + 1;  
  72.         // 查询已经下载的记录  
  73.         downloadedLength = this.getDownloadedLength(path);  
  74.     }  
  75.   
  76.     private Map<Integer, Integer> getDownloadedLength(String path) {  
  77.         SQLiteDatabase db = dbHelper.getReadableDatabase();  
  78.         String sql = "SELECT threadId,downLength FROM fileDownloading WHERE downPath=?";  
  79.         Cursor cursor = db.rawQuery(sql, new String[] { path });  
  80.         Map<Integer, Integer> data = new HashMap<Integer, Integer>();  
  81.         while (cursor.moveToNext()) {  
  82.             data.put(cursor.getInt(0), cursor.getInt(1));  
  83.         }  
  84.         db.close();  
  85.         return data;  
  86.     }  
  87.   
  88.     private String getFileName(HttpURLConnection conn) {  
  89.         String fileName = path.substring(path.lastIndexOf("/") + 1, path.length());  
  90.         if (fileName == null || "".equals(fileName.trim())) {  
  91.             String content_disposition = null;  
  92.             for (Entry<String, List<String>> entry : conn.getHeaderFields().entrySet()) {  
  93.                 if ("content-disposition".equalsIgnoreCase(entry.getKey())) {  
  94.                     content_disposition = entry.getValue().toString();  
  95.                 }  
  96.             }  
  97.             try {  
  98.                 Matcher matcher = Pattern.compile(".*filename=(.*)").matcher(content_disposition);  
  99.                 if (matcher.find()) fileName = matcher.group(1);  
  100.             } catch (Exception e) {  
  101.                 fileName = UUID.randomUUID().toString() + ".tmp"// 默认名  
  102.             }  
  103.         }  
  104.         return fileName;  
  105.     }  
  106.   
  107.     public void download(DownloadListener listener) throws Exception {  
  108.         this.deleteDownloading(); // 先删除上次的记录,再重新添加  
  109.         for (int i = 0; i < threads.length; i++) {  
  110.             threads[i] = new MultiThreadDownload(i, savedFile, block, path, downloadedLength.get(i), this);  
  111.             new Thread(threads[i]).start();  
  112.         }  
  113.         this.saveDownloading(threads);  
  114.   
  115.         while (!isFinish(threads)) {  
  116.             Thread.sleep(900);  
  117.             if (listener != null) listener.onDownload(getDownloadedSize(threads));  
  118.             this.updateDownloading(threads);  
  119.         }  
  120.         if (!this.isPause) this.deleteDownloading();// 完成下载之后删除本次下载记录  
  121.     }  
  122.   
  123.     private void saveDownloading(MultiThreadDownload[] threads) {  
  124.         SQLiteDatabase db = dbHelper.getWritableDatabase();  
  125.         try {  
  126.             db.beginTransaction();  
  127.             for (MultiThreadDownload thread : threads) {  
  128.                 String sql = "INSERT INTO fileDownloading(downPath,threadId,downLength) values(?,?,?)";  
  129.                 db.execSQL(sql, new Object[] { path, thread.id, 0 });  
  130.             }  
  131.             db.setTransactionSuccessful();  
  132.         } finally {  
  133.             db.endTransaction();  
  134.             db.close();  
  135.         }  
  136.     }  
  137.   
  138.     private void deleteDownloading() {  
  139.         SQLiteDatabase db = dbHelper.getWritableDatabase();  
  140.         String sql = "DELETE FROM fileDownloading WHERE downPath=?";  
  141.         db.execSQL(sql, new Object[] { path });  
  142.         db.close();  
  143.     }  
  144.   
  145.     private void updateDownloading(MultiThreadDownload[] threads) {  
  146.         SQLiteDatabase db = dbHelper.getWritableDatabase();  
  147.         try {  
  148.             db.beginTransaction();  
  149.             for (MultiThreadDownload thread : threads) {  
  150.                 String sql = "UPDATE fileDownloading SET downLength=? WHERE threadId=? AND downPath=?";  
  151.                 db.execSQL(sql, new String[] { thread.currentDownloadSize + "", thread.id + "", path });  
  152.             }  
  153.             db.setTransactionSuccessful();  
  154.         } finally {  
  155.             db.endTransaction();  
  156.             db.close();  
  157.         }  
  158.     }  
  159.   
  160.     private int getDownloadedSize(MultiThreadDownload[] threads) {  
  161.         int sum = 0;  
  162.         for (int len = threads.length, i = 0; i < len; i++) {  
  163.             sum += threads[i].currentDownloadSize;  
  164.         }  
  165.         return sum;  
  166.     }  
  167.   
  168.     private boolean isFinish(MultiThreadDownload[] threads) {  
  169.         try {  
  170.             for (int len = threads.length, i = 0; i < len; i++) {  
  171.                 if (!threads[i].finished) {  
  172.                     return false;  
  173.                 }  
  174.             }  
  175.             return true;  
  176.         } catch (Exception e) {  
  177.             return false;  
  178.         }  
  179.     }  
  180. }  


运行效果:

 


源码下载地址

 

http://blog.csdn.net/xiangzhihong8/article/details/17089989    android 多线程断点续传下载 三

目录
相关文章
|
2月前
|
Java Android开发 UED
🧠Android多线程与异步编程实战!告别卡顿,让应用响应如丝般顺滑!🧵
【7月更文挑战第28天】在Android开发中,确保UI流畅性至关重要。多线程与异步编程技术可将耗时操作移至后台,避免阻塞主线程。我们通常采用`Thread`类、`Handler`与`Looper`、`AsyncTask`及`ExecutorService`等进行多线程编程。
47 2
|
4月前
|
Java 数据库 Android开发
【专栏】Kotlin在Android开发中的多线程优化,包括线程池、协程的使用,任务分解、避免阻塞操作以及资源管理
【4月更文挑战第27天】本文探讨了Kotlin在Android开发中的多线程优化,包括线程池、协程的使用,任务分解、避免阻塞操作以及资源管理。通过案例分析展示了网络请求、图像处理和数据库操作的优化实践。同时,文章指出并发编程的挑战,如性能评估、调试及兼容性问题,并强调了多线程优化对提升应用性能的重要性。开发者应持续学习和探索新的优化策略,以适应移动应用市场的竞争需求。
95 5
|
4月前
|
Java 调度 Android开发
构建高效Android应用:探究Kotlin多线程编程
【2月更文挑战第17天】 在现代移动开发领域,性能优化一直是开发者关注的焦点。特别是在Android平台上,合理利用多线程技术可以显著提升应用程序的响应性和用户体验。本文将深入探讨使用Kotlin进行Android多线程编程的策略与实践,旨在为开发者提供系统化的解决方案和性能提升技巧。我们将从基础概念入手,逐步介绍高级特性,并通过实际案例分析如何有效利用Kotlin协程、线程池以及异步任务处理机制来构建一个更加高效的Android应用。
|
4月前
|
Java 调度 数据库
Android 性能优化: 如何进行多线程编程以提高应用性能?
Android 性能优化: 如何进行多线程编程以提高应用性能?
103 0
|
29天前
|
数据采集 XML JavaScript
C# 中 ScrapySharp 的多线程下载策略
C# 中 ScrapySharp 的多线程下载策略
|
8天前
|
Java 数据库 Android开发
一个Android App最少有几个线程?实现多线程的方式有哪些?
本文介绍了Android多线程编程的重要性及其实现方法,涵盖了基本概念、常见线程类型(如主线程、工作线程)以及多种多线程实现方式(如`Thread`、`HandlerThread`、`Executors`、Kotlin协程等)。通过合理的多线程管理,可大幅提升应用性能和用户体验。
25 15
一个Android App最少有几个线程?实现多线程的方式有哪些?
|
1天前
|
Java Android开发 UED
🧠Android多线程与异步编程实战!告别卡顿,让应用响应如丝般顺滑!🧵
在Android开发中,为应对复杂应用场景和繁重计算任务,多线程与异步编程成为保证UI流畅性的关键。本文将介绍Android中的多线程基础,包括Thread、Handler、Looper、AsyncTask及ExecutorService等,并通过示例代码展示其实用性。AsyncTask适用于简单后台操作,而ExecutorService则能更好地管理复杂并发任务。合理运用这些技术,可显著提升应用性能和用户体验,避免内存泄漏和线程安全问题,确保UI更新顺畅。
12 5
|
10天前
|
Java 数据库 Android开发
一个Android App最少有几个线程?实现多线程的方式有哪些?
本文介绍了Android应用开发中的多线程编程,涵盖基本概念、常见实现方式及最佳实践。主要内容包括主线程与工作线程的作用、多线程的多种实现方法(如 `Thread`、`HandlerThread`、`Executors` 和 Kotlin 协程),以及如何避免内存泄漏和合理使用线程池。通过有效的多线程管理,可以显著提升应用性能和用户体验。
30 10
|
1月前
|
调度 Android开发 开发者
【颠覆传统!】Kotlin协程魔法:解锁Android应用极速体验,带你领略多线程优化的无限魅力!
【8月更文挑战第12天】多线程对现代Android应用至关重要,能显著提升性能与体验。本文探讨Kotlin中的高效多线程实践。首先,理解主线程(UI线程)的角色,避免阻塞它。Kotlin协程作为轻量级线程,简化异步编程。示例展示了如何使用`kotlinx.coroutines`库创建协程,执行后台任务而不影响UI。此外,通过协程与Retrofit结合,实现了网络数据的异步加载,并安全地更新UI。协程不仅提高代码可读性,还能确保程序高效运行,不阻塞主线程,是构建高性能Android应用的关键。
37 4
|
30天前
|
数据处理 Python
解锁Python多线程编程魔法,告别漫长等待!让数据下载如飞,感受科技带来的速度与激情!
【8月更文挑战第22天】Python以简洁的语法和强大的库支持在多个领域大放异彩。尽管存在全局解释器锁(GIL),Python仍提供多线程支持,尤其适用于I/O密集型任务。通过一个多线程下载数据的例子,展示了如何使用`threading`模块创建多线程程序,并与单线程版本进行了性能对比。实验表明,多线程能显著减少总等待时间,但在CPU密集型任务上GIL可能会限制其性能提升。此案例帮助理解Python多线程的优势及其适用场景。
26 0