当前位置: 移动技术网 > IT编程>脚本编程>Python > Python3使用线程

Python3使用线程

2019年08月28日  | 移动技术网IT编程  | 我要评论

记忆论坛,我们结婚了20121110,美女恶搞

python2标准库中提供了两个模块thread和threading支持多线程。
thread有一些缺陷在python3中弃用,为了兼容性,python3 将 thread 重命名为 "_thread",在python3中推荐直接使用threading。

创建线程对象

class threading.thread(group=none, target=none, name=none, args=(), kwargs={}, *, daemon=none)

参数说明:

group 应该为 none;为了日后扩展 threadgroup 类实现而保留。
target 是用于 run() 方法调用的可调用对象。默认是 none,表示不需要调用任何方法。
name 是线程名称。默认情况下,由 "thread-n" 格式构成一个唯一的名称,其中 n 是小的十进制数。
args 是用于调用目标函数的参数元组。默认是 ()。
kwargs 是用于调用目标函数的关键字参数字典。默认是 {}。
如果 daemon 不是 none,线程将被显式的设置为 守护模式,不管该线程是否是守护模式。如果是 none (默认值),线程将继承当前线程的守护模式属性。

线程对象其中的几个方法

start()
开始线程活动。
run()
代表线程活动的方法。
join(timeout=none)
等待,直到线程终结

使用线程有两种方式:函数或者用类来包装线程对象

例子1:使用函数

import random
import threading 
import time

def run(threadname):
    for i in range(5):
        time.sleep(random.random())
        print('{} : {}'.format(threadname, i))

t1 = threading.thread(target=run, args=('thread 1',))
t1.start()
t2 = threading.thread(target=run, args=('thread 2',))
t2.start()

例子2:使用类

import random
import threading 
import time

class test(threading.thread):
    def __init__(self,name):
        super().__init__()
        self.name = name
    def run(self):
        for i in range(5):
            time.sleep(random.random())
            print('{} : {}'.format(self.name, i))
        
t1 = test('thread 1')
t1.start()
t2 = test('thread 2')
t2.start()

例子1和例子2某次运行结果:

thread 1 : 0
thread 1 : 1
thread 2 : 0
thread 1 : 2
thread 2 : 1
thread 2 : 2
thread 1 : 3
thread 2 : 3
thread 2 : 4
thread 1 : 4

例子3:

import random
import threading 
import time

def run(threadname,):
    print('{} start'.format(threadname))
    time.sleep(random.random())
    print('{} end'.format(threadname))

threads = []

#创建10个线程对象
for i in range(10):
    threads.append(threading.thread(target=run,args=('thread ' + str(i),)))

#运行线程
for th in threads:
    th.start()

#等待,直到线程终结。
for th in threads:
    th.join()

print("finished")

某次运行结果:

thread 0 start
thread 1 start
thread 2 start
thread 3 start
thread 4 start
thread 5 start
thread 6 start
thread 7 start
thread 8 start
thread 9 start
thread 2 end
thread 3 end
thread 9 end
thread 0 end
thread 1 end
thread 8 end
thread 6 end
thread 4 end
thread 7 end
thread 5 end
finished

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网