1
import threading import time from threading import current_thread def myThread(arg1, arg2): print(current_thread().getName(),'start') print('%s %s'%(arg1, arg2)) time.sleep(1) print(current_thread().getName(),'stop') for i in range(1,4,1): # t1 = myThread(i, i+1) t1 = threading.Thread(target=myThread,args=(i, i+1)) t1.start() print(current_thread().getName(),'end') # 运行结果 Thread-1 start 1 2 Thread-2 start 2 3 Thread-3 start 3 4 MainThread end Thread-2 stop Thread-1 stop Thread-3 stop
2
import threading from threading import current_thread class Mythread(threading.Thread): def run(self): print(current_thread().getName(),'start') print('run') print(current_thread().getName(),'stop') t1 = Mythread() t1.start() t1.join() print(current_thread().getName(),'end') # 运行结果 Thread-1 start run Thread-1 stop MainThread end
3. 生产者和消费者
from threading import Thread,current_thread import time import random from queue import Queue queue = Queue(5) class ProducerThread(Thread): def run(self): name = current_thread().getName() nums = range(100) global queue while True: num = random.choice(nums) queue.put(num) print('生产者 %s 生产了数据 %s' %(name, num)) t = random.randint(1,3) time.sleep(t) print('生产者 %s 睡眠了 %s 秒' %(name, t)) class ConsumerTheard(Thread): def run(self): name = current_thread().getName() global queue while True: num = queue.get() queue.task_done() print('消费者 %s 消耗了数据 %s' %(name, num)) t = random.randint(1,5) time.sleep(t) print('消费者 %s 睡眠了 %s 秒' % (name, t)) p1 = ProducerThread(name = 'p1') p1.start() p2 = ProducerThread(name = 'p2') p2.start() p3 = ProducerThread(name = 'p3') p3.start() c1 = ConsumerTheard(name = 'c1') c1.start() c2 = ConsumerTheard(name = 'c2') c2.start() # 运行结果 生产者 p1 生产了数据 76 生产者 p2 生产了数据 89 生产者 p3 生产了数据 37 消费者 c1 消耗了数据 76 消费者 c2 消耗了数据 89 Execution Timed Out undefined