• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Python如何生成线程

python 搞java代码 3年前 (2022-05-21) 35次浏览 已收录 0个评论

Python中有两个线程模块,分别是threadthreading,threading是thread的升级版。threading的功能更强大。

创建线程有3种方法:

1、thread模块的start_new_thread函数

2、继承自threading.Thread模块

3、用theading.Thread直接返回一个thread对象,然后运行它的start方法

方法一、thread模块的start_new_thread函数

其函数原型:

start_new_thread(function,atgs[,kwargs])

www#gaodaima.com来源gao($daima.com搞@代@#码网搞代码

其参数含义如下:

function: 在线程中执行的函数名
args:元组形式的参数列表。
kwargs: 可选参数,以字典的形式指定参数(即对一些参数进行指定初始化)

代码

import thread
 
def hello(id = 0, interval = 2):
    for i in filter(lambda x: x % interval == 0, range(10)):
        print "Thread id : %d, time is %d
" % (id, i)
 
if __name__ == "__main__":
 
    #thread.start_new_thread(hello, (1,2))   这种调用形式也是可用的
    #thread.start_new_thread(hello, (2,4))
     
    thread.start_new_thread(hello, (), {"id": 1})
    thread.start_new_thread(hello, (), {"id": 2})

方法二:继承自threading.Thread模块

注意:必须重写run函数,而且想要运行应该调用start方法

import threading
 
class MyThread(threading.Thread):
 
    def __init__(self, id, interval):
        threading.Thread.__init__(self)
 
        self.id = id
        self.interval = interval
 
    def run(self):
        for x in filter(lambda x: x % self.interval == 0, range(10)):
            print "Thread id : %d   time is %d 
" % (self.id, x)
 
if __name__ == "__main__":
    t1 = MyThread(1, 2)
    t2 = MyThread(2, 4)
 
    t1.start()
    t2.start()
 
    t1.join()
    t2.join()

方法三:用theading.Thread直接返回一个thread对象,然后运行它的start方法

import threading
 
def hello(id, times):
    for i in range(times):
        print "hello %s time is %d
" % (id , i)
 
if __name__ == "__main__":
    t = threading.Thread(target=hello, args=("hawk", 5))
    t.start()

来源:搞代码网:原文地址:https://www.gaodaima.com


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Python如何生成线程

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址