[python 学习] python 多线程

 

1、

# -*- coding: utf-8 -*-
import threading
import time
import random

def go(name):
    for i in range(2):
        integer = random.randint(0,10)
        print u'{} 前进{} 步.'.format(name,integer)
        time.sleep(2)

def back(name):
    for j in range(500):
        integer = random.randint(0,10)
        print u'{} 后退{} 步.'.format(name,integer)
        time.sleep(1)
  
if __name__ == '__main__':
    t1 = threading.Thread(target=go,args=('go',))
    t2 = threading.Thread(target=back,args=('back',))  
    t1.start()
    t2.start()
    print 'stop stop stop'

 

上面的 go() 和 back() 交替休眠,谁获得执行权谁执行。(教随机)

2、经典的生产者消费者,两个线程能够 " 沟通 " 。

# -*- coding: utf-8 -*-
import threading
import time
import random
import sys

def product(condition):
    global integers
    while True:
        condition.acquire() #获得锁 
        print u'狗粮生产机启动.................................'
        while integers < 100:
            time.sleep(1)            
            integer = random.randint(0,10) #生产
            integers = integers + integer
            print u'生产了 {} 颗狗粮,总共 {} 颗狗粮'.format(integer,integers)
            if integer in [6,8]:
                print u'上次生产了 {} 颗狗粮,狗粮生产机要休息休息了,唤醒单身去吃狗粮'.format(integer)
                break
        print u'狗粮生产机停止................................'
        condition.notify() #通知
        #condition.wait()
        condition.release() #释放锁

def customer(condition):
    global integers
    while True:
        condition.acquire() #获得锁
        while integers > 0:
            time.sleep(1)            
            integer = random.randint(0,10)
            integers_tmp = integers - integer
            if integers_tmp < 0:
                integer = integers
                integers = 0
                print u'单身狗吃 {} 颗狗粮,没有狗粮,汪汪汪...'.format(integer)                
            else:
                integers = integers - integer
                print u'单身狗吃 {} 颗狗粮,还有 {} 狗粮.'.format(integer,integers)
        condition.notify() #通知
        #condition.wait()
        condition.release()#释放锁
  
if __name__ == '__main__':
    integers = 0
    condition = threading.Condition()
    t1 = threading.Thread(target=product,args=(condition,))
    t2 = threading.Thread(target=customer,args=(condition,))  
    t1.start()
    t2.start()

上面的狗粮生产机(生产者)和单身狗(消费者),一个生产狗粮,一个吃狗粮。

posted @ 2017-08-31 16:43  S3c0ldW4ng  阅读(174)  评论(0编辑  收藏  举报