python多线程_使用Threading

转载自上海-悠悠:https://www.cnblogs.com/yoyoketang/p/8269713.html

python提供了两个模块来实现多线程thread 和threading ,thread 有一些缺点,在threading 得到了弥补,为了不浪费你和时间,所以我们直接学习threading 就可以了。

Python中使用线程有两种方式:函数或者用类来包装线程对象

1、threading.Thread参数介绍:

class Thread(_Verbose)
   
   __init__(self, group=None, target=None, name=None, args=(), kwargs=None, verbose=None)
       
       *group*:group参数必须为空,参数group是预留的,用于将来扩展;
       
       *target*: 参数target是一个可调用对象(也称为活动[activity]),在线程启动后执行
       
       *name*: 参数name是线程的名字。默认值为“Thread-N“,N是一个数字。
      
       *args*:传递给线程函数target的参数,他必须是个tuple类型.
       
       *kwargs*:kwargs表示关键字参数。字典类型 {}.

2、函数式  

1)不带参数

# 多进程函数式-无参数
import threading
import time
def eat():
    print("%s吃着火锅开始"%time.ctime())
    time.sleep(1)
    print("%s吃着火锅:涮羊肉"%time.ctime())
    time.sleep(1)
    print("%s吃着火锅:涮牛肉" % time.ctime())
    time.sleep(1)
    print("%s吃火锅结束" % time.ctime())

def listen():
    print("%s听音乐开始"%time.ctime())
    time.sleep(1)
    print("%s听音乐111"%time.ctime())
    time.sleep(1)
    print("%s听音乐222"%time.ctime())
    time.sleep(1)
    print("%s听音乐结束"%time.ctime())

if __name__ == '__main__':
    threads=[]#创建线程组数
    #创建线程1,并添加到线程组数
    t1=threading.Thread(target=eat)
    threads.append(t1)
    #创建线程2,并添加到线程组数
    t2=threading.Thread(target=listen)
    threads.append(t2)
    #启动线程
    for i in threads:
        i.start()

2)带参数

# 多进程函数式-带参数
import threading
import time
def eat(threadname,name):
    print("%s吃着%s开始"%(time.ctime(),threadname))
    time.sleep(1)
    print("%s吃着火锅:涮羊肉"%time.ctime())
    time.sleep(1)
    print("%s吃着火锅:涮牛肉" % time.ctime())
    time.sleep(1)
    print("%s吃%s结束" % (time.ctime(),threadname))
    print("%s运行结束"%name)

def listen(threadname):
    print("%s听%s开始"%(time.ctime(),threadname))
    time.sleep(1)
    print("%s听音乐111"%time.ctime())
    time.sleep(1)
    print("%s听音乐222"%time.ctime())
    time.sleep(1)
    print("%s听音乐结束"%time.ctime())

if __name__ == '__main__':
    threads=[]#创建线程组数
    #参数使用args,传元组
    t1=threading.Thread(target=eat,args=("火锅","吃火锅",))
    #参数使用kwargs,传字典
    # t1=threading.Thread(target=eat,kwargs={"threadname":"火锅","name":"吃火锅"})
    threads.append(t1)
    t2=threading.Thread(target=listen,args=("音乐",))
    threads.append(t2)
    #启动线程
    for i in threads:
        i.start()

 

 注意:参数后面需要多加一个“,”,不然会报错。

3、使用类封装

 

classThread(_Verbose) __init__(self, group=None, target=None, name=None, args=(), kwargs=None, verbose=None) *group*:group参数必须为空,参数group是预留的,用于将来扩展;     参数args和kwargs分别表示调用target时的参数列表和关键字参数。 *target*: 参数target是一个可调用对象(也称为活动[activity]),在线程启动后执行 *name*: 参数name是线程的名字。默认值为“Thread-N“,N是一个数字。 *args*:传递给线程函数target的参数,他必须是个tuple类型. *kwargs*:kwargs表示关键字参数。字典类型 {}.

猜你喜欢

转载自www.cnblogs.com/crystal1126/p/12808304.html
今日推荐