python,多线程应用示例

应用python的threading模块开启多线程执行程序,会缩短程序运行时间,下面代码演示了多线程应用

#不开启多线程演示
import time,threading
def foo(n):
    print('foo%s'%n)
    time.sleep(1)
def bar(n):
    print('bar%s'%n)
    time.sleep(2)
begin = time.time()
t1 = threading.Thread(target = foo,args = (1,))
t2 = threading.Thread(target = bar,args = (2,))
#t1.start()
#t2.start()
foo(1)
bar(2)
end = time.time()
process_time = end - begin
print('process time is:%s'%(str(process_time)))

上面不开启多线程的情况下执行结果如下:

/usr/bin/python3.6 /home/guoming/python/day27/thread.py
foo1
bar2
process time is:3.003460168838501

Process finished with exit code 0
程序运行花了3秒时间

#改写一下,开启两个线程
import time,threading
def foo(n):
print('foo%s'%n)
time.sleep(1)
def bar(n):
print('bar%s'%n)
time.sleep(2)
begin = time.time()
t1 = threading.Thread(target = foo,args = (1,))
t2 = threading.Thread(target = bar,args = (2,))
t1.start()
t2.start()
#foo(1)
#bar(2)


print('......main.........')
t1.join()
t2.join()
end = time.time()
process_time = end - begin
print('process time is:%s'%(str(process_time)))

开启线程后执行结果如下:

/usr/bin/python3.6 /home/guoming/python/day27/thread.py
foo1
bar2
......main.........
process time is:2.0026726722717285

Process finished with exit code 0
程序用了2秒

posted @ 2019-12-14 11:52  Iceberg_710815  阅读(325)  评论(0编辑  收藏  举报