import time
# 单线程
def sayHello(index):
print('hello!', index)
time.sleep(1)
print('执行完成')
for i in range(5):
sayHello(i)
结果:
例子中看单线程程序执行呢就是一个接着一个执行
多线程:
import time
import threading
def sayHello(index):
print('hello!', index)
time.sleep(1)
print('执行完成')
for i in range(5):
t1 = threading.Thread(target=sayHello, args=(i,))
t1.start()
Thread(group=None, target=None, name=None, args=(), kwargs=None, *, daemon=None)
|*group* should be None; reserved for future extension when a ThreadGroup
|class is implemented.
|
|*target* is the callable object to be invoked by the run()
|method. Defaults to None, meaning nothing is called.
|
|*name* is the thread name. By default, a unique name is constructed of
|the form "Thread-N"where N is a small decimal number.
|
|*args* is the argument tuple for the target invocation. Defaults to ().
|
|*kwargs* is a dictionary of keyword arguments for the target
|invocation. Defaults to {}.
target就是线程启动后执行的函数
args和kwargs都是这个函数的参数,args是元组类型,kwargs是关键字类型参数。
name是给这个线程的名字,如果不传就是Thread-1, Thread-2....
它还有一些方法:
run(): 执行线程中的方法。
start(): 启动线程。
join(): 等待线程结束。
isAlive(): 返回线程是否活动的。
getName(): 返回线程名。
setName(): 设置线程名。
threading.currentThread
threading.currentThread可以获得当前的线程信息,例子:
import time
from threading import Thread, currentThread
def sayHello(index):
print(currentThread().getName(), index)
time.sleep(1)
print('执行完成')
for i in range(5):
t1 = Thread(target=sayHello, kwargs={'index': 1})
t1.start()
结果:
结合Thread类的join方法,可以看下主线程和子线程之间的顺序:
from threading import Thread, currentThread
import time
def do_somethong():
print(currentThread().getName(), '开始')
time.sleep(1)
print(currentThread().getName(), '结束')
t1 = Thread(target=do_somethong)
t1.start()
print(currentThread().getName(), '结束')
from threading import Thread
a = 0
def change_num(num):
global a
a += 1
a -= 1
def run_thread(num):
for i in range(100000):
change_num(num)
t1 = Thread(target=run_thread, args=(1,))
t2 = Thread(target=run_thread, args=(2,))
t1.start()
t2.start()
t1.join()
t2.join()
print(a)