Python threading多线程编程实例
Python 的多线程有两种实现方法:
函数,线程类
1.函数
调用 thread 模块中的 start_new_thread() 函数来创建线程,以线程函数的形式告诉线程该做什么
# -*- coding: utf-8 -*-
import thread
def f(name):
#定义线程函数
print "this is " + name
if __name__ == '__main__':
thread.start_new_thread(f, ("thread1",))
#用start_new_thread()调用线程函数和其他参数
while 1:
pass
不过这种方法暂时没能找到其他辅助方法,连主线程等待都要用 while 1 这种方法解决。
2.线程类
调用 threading 模块,创建 threading.Thread 的子类来得到自定义线程类。
# -*- coding: utf-8 -*-
import threading
class Th(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.t_name = name
#调用父类构造函数
def run(self):
#重写run()函数,线程默认从此函数开始执行
print "This is " + self.t_name
if __name__ == '__main__':
thread1 = Th("Thread_1")
thread1.start()
#start()函数启动线程,自动执行run()函数
threading.Thread 类的可继承函数:
getName() 获得线程对象名称
setName() 设置线程对象名称
join() 等待调用的线程结束后再运行之后的命令
setDaemon(bool) 阻塞模式, True: 父线程不等待子线程结束, False 等待,默认为 False
isDaemon() 判断子线程是否和父线程一起结束,即 setDaemon() 设置的值
isAlive() 判断线程是否在运行
实例
import threading
import time
class Th(threading.Thread):
def __init__(self, thread_name):
threading.Thread.__init__(self)
self.setName(thread_name)
def run(self):
print "This is thread " + self.getName()
for i in range(5):
time.sleep(1)
print str(i)
print self.getName() + "is over"
join() 阻塞等待
if __name__ == '__main__':
thread1 = Th("T1 ")
thread1.start()
#thread1.join()
print "main thread is over"
不带 thread1.join() ,得到如下结果:
This is thread T1
main thread is over
0
1
2
T1 is over
不等待 thread1 完成,执行之后语句。
加了 thread1.join() ,得到如下结果:
This is thread T1
0
1
2
T1 is over
main thread is over
阻塞等待 thread1 结束,才执行下面语句
主线程等待
if __name__ == '__main__':
thread1 = Th("T1 ")
thread1.setDaemon(True)
#要在线程执行之前就设置这个量
thread1.start()
print "main thread is over"
报错: Exception in thread T1 (most likely raised during interpreter shutdown):
也就是主线程不等待子线程就结束了。
多个子线程
if __name__ == '__main__':
for i in range(3):
t = Th(str(i))
t.start()
print "main thread is over"
这里的 t 可同时处理多个线程,即 t 为线程句柄,重新赋值不影响线程。
这里奇怪的是,运行 t.run() 时,不会再执行其他线程。虽不明,还是用 start() 吧。暂且理解为 start() 是非阻塞并行的,而 run 是阻塞的。
线程锁
threading 提供线程锁,可以实现线程同步。
import threading
import time
class Th(threading.Thread):
def __init__(self, thread_name):
threading.Thread.__init__(self)
self.setName(thread_name)
def run(self):
threadLock.acquire()
#获得锁之后再运行
print "This is thread " + self.getName()
for i in range(3):
time.sleep(1)
print str(i)
print self.getName() + " is over"
threadLock.release()
#释放锁
if __name__ == '__main__':
threadLock = threading.Lock()
#设置全局锁
thread1 = Th('Thread_1')
thread2 = Th('Thread_2')
thread1.start()
thread2.start()
得到结果:
This is thread Thread_1
0
1
2
Thread_1 is over
This is thread Thread_2
0
1
2
Thread_2 is over

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".
