Python多线程编程

By 刘志军 , 2014-02-17, 分类: python

python

python2.4前有个thread模块支持多线程编程,2.4后新增了threading模块,提供更高级别和更强大的线程支持.

除此之外,threading提供了很多和java中Thread类一样的方法:(注意这是都是实例方法)

创建线程的方式有两种:

1)继承threading.Thread

a.创建一个threading.Thread的子类
b.覆盖__init__(self [,args])
c.重写run方法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#!/usr/bin/python 
#!coding=utf-8
import threading
import time
exitFlag = 0
class MyThread(threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter

    def run(self):
        task()

    def task(self):
       '''线程要执行的任务'''
       print 'starting ' + self.name
       print 'exiting ' + self.name

#创建线程
thread1 = MyThread(1,'Thread-1', 1)
thread2 = MyThread(2,'Thread-2', 2)

#启动线程
thread1.start()
thread2.start()

#等待线程结束
thread1.join()
thread2.join()

print 'exiting main thread'

2)任务函数作为参数传递到Thread方法中

threading.Thread(target=task, args=()).start()

关注公众号「Python之禅」,回复「1024」免费获取Python资源

python之禅

猜你喜欢

2016-12-07
好玩的Python彩蛋
2023-04-15
如何删除macOS系统默认的Python2.7并替换成最新版python3.11
2017-10-29
Python每日一题:第1题
2017-12-26
5个酷毙的Python工具
2020-12-25
PDF转换库 WeasyPrint 使用指南
2019-11-21
自己动手写个"狗屁不通"文章生成器
2014-02-10
python 函数式编程处理函数:map(),filter(),reduce()
2014-03-26
斐波那契数列(Fibonacci)递归与非递归的性能对比
2022-08-17
如何利用多态干掉 if else 语句
2017-07-19
如何正确理解@classmethod与@staticmethod