来自 编程应用 2019-09-04 19:46 的文章
当前位置: 六合联盟网 > 编程应用 > 正文

python成立线程示例

复制代码 代码如下:

from time import ctime,sleep

import threading
from time import sleep

def music():
for i in range(2):
print ("I was listening to music. %s" %ctime())
sleep(1)

def test_func(id):
    for i in range(0,5):
        sleep(1)
        print('thread %d is running %d' % (id,i))

def move():
for i in range(2):
print ("I was at the movies! %s" %ctime())
sleep(5)

threads = []
for i in range(0,3):
    t = threading.Thread(target=test_func, args=(i,))
    threads.append(t)

if __name__ == '__main__':
music()
move()
print ("all over %s" %ctime())

for t in threads:
    t.start()

 

for t in threads:
    t.join()

import threading
from time import ctime,sleep

从出口结果能够看看,3个线程是轮流的推行的

def music(func):
for i in range(2):
print ("I was listening to %s. %s" %(func,ctime()))
sleep(1)

 

def move(func):
for i in range(2):
print ("I was at the %s! %s" %(func,ctime()))
sleep(5)

代码如下: import threading from time import sleep def test_func(id): for i in range(0,5): sleep(1) print('thread %d is running %d' % (id,i)) threads = [] for i in...

 

if __name__ == '__main__':
music("test1")
move("test2")

print ("all over %s" %ctime())

#coding=utf-8
import threading
from time import ctime,sleep

def music(func):
for i in range(2):
print("I was listening to %s. %s" %(func,ctime()))
sleep(1)

def move(func):
for i in range(2):
print ("I was at the %s! %s" %(func,ctime()))
sleep(5)

threads = []
t1 = threading.Thread(target=music,args=(u'test1',))
threads.append(t1)
t2 = threading.Thread(target=move,args=(u'Test2',))
threads.append(t2)

if __name__ == '__main__':
for t in threads:
t.setDaemon(True)
t.start()

print ("all over %s" %ctime())

其三局地线程职责管理。

本文由六合联盟网发布于编程应用,转载请注明出处:python成立线程示例

关键词: