Python多线程编程

函数的方法

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,6,1):
    # t1 = myThread(i,i+1)
    t1 = threading.Thread(target=myThread,args=(i,i+1))
    t1.start()

print(current_thread().getName(),'end')

类的方法

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()

生产者与消费者练习

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 ConsumerThread(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()
p1.start()
p2=ProducerThread()
p2.start()
p3=ProducerThread()
p3.start()
c1 = ConsumerThread()
c1.start()
c2 = ConsumerThread()
c2.start()
此条目发表在Python分类目录。将固定链接加入收藏夹。

发表评论

电子邮件地址不会被公开。 必填项已用*标注

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

Protected with IP Blacklist CloudIP Blacklist Cloud