Python学习笔记12——多线程threading

代码如下:
author = 'damao'

import time
import threading

"""单线程"""
# 所谓单线程及为做事件要按顺序一件一件来
def eat():
    print("{a}开始吃饭".format(a=time.ctime()))
    time.sleep(1)
    print("{a}吃饭结束".format(a=time.ctime()))

def read():
    print("{a}开始读书".format(a=time.ctime()))
    time.sleep(1)
    print("{a}读书完毕".format(a=time.ctime()))


"""见到多线程案例"""
def eat_food():
    print("{a}开始吃饭".format(a=time.ctime()))
    time.sleep(1)
    print("{a}下酒菜:红烧鱼".format(a=time.ctime()))
    time.sleep(1)
    print("{a}下酒菜:黄焖鸡".format(a=time.ctime()))
    time.sleep(1)
    print("{a}吃饭结束".format(a=time.ctime()))

def read_book():
    print("{a}开始读书".format(a=time.ctime()))
    time.sleep(1)
    print("{a}读着python".format(a=time.ctime()))
    time.sleep(1)
    print("{a}读着Linux".format(a=time.ctime()))
    time.sleep(1)
    print("{a}读书完毕".format(a=time.ctime()))
# 创建线程数组
threads = []
t1 = threading.Thread(target=eat_food)
threads.append(t1)
t2 = threading.Thread(target=read_book)
threads.append(t2)


"""带参数的多进程"""
def eat_food_one(name):
    print("{a}开始吃饭".format(a=time.ctime()),name)
    time.sleep(1)
    print("{a}下酒菜:红烧鱼".format(a=time.ctime()))
    time.sleep(1)
    print("{a}下酒菜:黄焖鸡".format(a=time.ctime()))
    time.sleep(1)
    print("{a}吃饭结束".format(a=time.ctime()))

def read_book_one(thread_name):
    print("{a}开始读书".format(a=time.ctime()),thread_name)
    time.sleep(1)
    print("{a}读着python".format(a=time.ctime()))
    time.sleep(1)
    print("{a}读着Linux".format(a=time.ctime()))
    time.sleep(1)
    print("{a}读书完毕".format(a=time.ctime()))

my_thread = []
# mt_1 = threading.Thread(args=("大餐",))  # args 传入元组类型的参数时,最后一个参数要加上逗号,不然程序会报错
mt_1 = threading.Thread(target=eat_food_one,kwargs={'name':'大餐'}) # kwargs传入字典类型的参数
my_thread.append(mt_1)
mt_2 = threading.Thread(target=read_book_one,args=("好书",))
# mt_2 = threading.Thread(target=read_book_one,kwargs={'thread_name':'好书'})
my_thread.append(mt_2)




if __name__=="__main__":
    # eat()
    # read()
    # for i in threads
    #     i.start()
    for i in my_thread:
        i.start()

你可能感兴趣的:(Python学习笔记12——多线程threading)