一、多线程简单示例

import threading,time
print('第一线程(默认):程序开始啦!')
def takeANap():
time.sleep(5)
print('第二线程:5秒到,我醒来啦!') #创建并启动多线程
t=threading.Thread(target=takeANap)
t.start() print('第一线程(默认):程序结束啦!') '''
输出:
第一线程(默认):程序开始啦!
第一线程(默认):程序结束啦!
>>> 第二线程:5秒到,我醒来啦!
'''

二、多线程传递多参数、可选参数示例

import threading

##多线程传递多参数print('Cats','Dogs','Frogs',sep='&')=>Cats & Dogs & Frogs:
threadObj = threading.Thread(target=print, args=['Cats', 'Dogs', 'Frogs'],kwargs={'sep': ' & '})
threadObj.start() ##输出:Cats & Dogs & Frogs

三、并发问题

可以轻松地创建多个新线程,让它们同时运行。但多线程也可能会导致所谓的并发问题。如果这些线程同时读写变量,导致互相干扰,就会发生并发问题。并发问题可能很难一致地重现,所以难以调试。多线程编程本身就是一个广泛的主题。必须记住的是:为了避免并发问题,绝不让多个线程读取或写入相同的变量。当创建一个新的Thread 对象时,要确保其目标函数只使用该函数中的局部变量。这将避免程序中难以调试的并发问题。

多线程实战,多线程下载漫画

#! python3
# multidownloadXkcd.py - Downloads XKCD comics using multiple threads. import requests, os, bs4, threading
os.makedirs('xkcd', exist_ok=True) # store comics in ./xkcd def downloadXkcd(startComic, endComic):
for urlNumber in range(startComic, endComic):
# Download the page.
print('Downloading page http://xkcd.com/%s...' % (urlNumber))
res = requests.get('http://xkcd.com/%s' % (urlNumber))
res.raise_for_status() soup = bs4.BeautifulSoup(res.text) # Find the URL of the comic image.
comicElem = soup.select('#comic img')
if comicElem == []:
print('Could not find comic image.')
else:
comicUrl = comicElem[0].get('src')
# Download the image.
print('Downloading image %s...' % (comicUrl))
res = requests.get(comicUrl)
res.raise_for_status() # Save the image to ./xkcd
imageFile = open(os.path.join('xkcd', os.path.basename(comicUrl)), 'wb')
for chunk in res.iter_content(100000):
imageFile.write(chunk)
imageFile.close() # Create and start the Thread objects.
downloadThreads = [] # a list of all the Thread objects
for i in range(0, 1400, 100): # loops 14 times, creates 14 threads
downloadThread = threading.Thread(target=downloadXkcd, args=(i, i + 99))
downloadThreads.append(downloadThread)
downloadThread.start() # Wait for all threads to end.
for downloadThread in downloadThreads:
downloadThread.join()
print('Done.')

多线程(threading)示例的更多相关文章

  1. ASP.Net:Javascript 通过PageMethods 调用后端WebMethod方法 + 多线程数据处理 示例

    ASP.Net:Javascript 通过PageMethods 调用后端WebMethod方法 + 多线程数据处理 示例 2012年04月27日 16:59:16 奋斗的小壁虎 阅读数:4500   ...

  2. python多线程threading.Lock锁用法实例

    本文实例讲述了python多线程threading.Lock锁的用法实例,分享给大家供大家参考.具体分析如下: python的锁可以独立提取出来 mutex = threading.Lock() #锁 ...

  3. Python初学——多线程Threading

    接着上篇继续跟着沫凡小哥学Python啦 1.1 什么是多线程 Threading 多线程可简单理解为同时执行多个任务. 多进程和多线程都可以执行多个任务,线程是进程的一部分.线程的特点是线程之间可以 ...

  4. 多线程-threading

    多线程-threading python的thread模块是比较底层的模块,python的threading模块是对thread做了一些包装的,可以更加方便的被使用 1. 使用threading模块 ...

  5. python的多线程threading

    多线程threading 1.Thread创建线程: 上代码: #!/usr/bin/env python3 import threading import time def A(): t_name ...

  6. 多进程 multiprocessing 多线程Threading 线程池和进程池concurrent.futures

    multiprocessing.procsess 定义一个函数 def func():pass 在if __name__=="__main__":中实例化 p = process( ...

  7. python中多进程multiprocessing、多线程threading、线程池threadpool

    浅显点理解:进程就是一个程序,里面的线程就是用来干活的,,,进程大,线程小 一.多线程threading 简单的单线程和多线程运行:一个参数时,后面要加逗号 步骤:for循环,相当于多个线程——t=t ...

  8. 物无定味适口者珍,Python3并发场景(CPU密集/IO密集)任务的并发方式的场景抉择(多线程threading/多进程multiprocessing/协程asyncio)

    原文转载自「刘悦的技术博客」https://v3u.cn/a_id_221 一般情况下,大家对Python原生的并发/并行工作方式:进程.线程和协程的关系与区别都能讲清楚.甚至具体的对象名称.内置方法 ...

  9. python多线程threading下载示例

    #coding:utf-8 # windows中测试不通过,下载的图片不完整 # 通过多线程下载图片 import requests import threading class downloader ...

随机推荐

  1. 【PyQt5-Qt Designer】日历(QCalendarWidget)

    日历(QCalendarWidget)+爬虫API调用+自定义发送信号(传入2个参数) 总体介绍 QCalendarWidget类提供了一个基日历小部件,允许用户选择一个日期. 该小部件使用当前的月份 ...

  2. struts2 中的 addActionError 、addFieldError、addActionMessage的方法【转】

    一.addActionError("错误内容"):  Action级别的错误消息this.addActionError("错误信息1");this.addAct ...

  3. ASCLL码中的一些小知识

    其次要记住asill值中   65是A      97是a A与a之间相隔32,用int转换后再用char转换回来. char b = s.charAt(i);为字符串转换成一个一个的.

  4. SpringBoot-热部署Devtools

    热部署 什么是热部署 所谓的热部署:比如项目的热部署,就是在应用程序在不停止的情况下,实现新的部署 项目演示案例 @RestController @Slf4j public class IndexCo ...

  5. IAM:亚马逊访问权限控制

    IAM的策略.用户->服务器(仓库.业务体) IAM:亚马逊访问权限控制(AWS Identity and Access Management )IAM使您能够安全地控制用户对 AWS 服务和资 ...

  6. CentOS 7.2编译安装nginx1.10.3+MySQL5.5.38+PHP5.5.38

    1.关闭firewallad 关闭防火墙 systemctl stop firewalld.service 禁止firewall开机启动 systemctl disable firewalld.ser ...

  7. left outer join的on不起作用

    left outer join的on不起作用 Why and when a LEFT JOIN with condition in WHERE clause is not equivalent to ...

  8. 4 jmeter badboy脚本开发技术详解

    badboy中的检查点 以www.sogou.com搜索为例演示,搜索badboy. 1.打开badboy工具,点击红色按钮开始录制,在地址栏目中输入地址:www.sogou.com,回车. 2.输入 ...

  9. cxGrid常用属性设置

    OptionsView部分 是否使用表头分组:cxGrid1DBTableView1.OptionsView.GroupByBox 单元格高度自适应:cxGrid1DBTableView1.Optio ...

  10. 在function module 中向数据库插入数据

    http://www.sapjx.com/abap-function-module.html 1: 应该在function module 中向数据库插入数据