python之线程介绍及开启线程的两种方法案例

1 什么线程
线程就是一条流水线的工作过程,一个进程内至少有一个线程
进程只是一个资源单位
而进程内的线程才执行单位
 
2 为什么要多线程(进程vs线程)
1、同一进程下的多个线程共享该进程内的数据
2、线程的创建开销要远远小于进程的
 
3 如何用线程
 
方式一:
from threading import Thread
import time,random

def piao(name):
    print('%s is piaoing' %name)
    time.sleep(random.randint(1,3))
    print('%s is piao end' % name)

if __name__ == '__main__':
    t=Thread(target=piao,args=('alex',))
    t.start()
    print('主')

方式二:

from threading import Thread
import time,random

class Mythread(Thread):
    def run(self):
        print('%s is piaoing' %self.name)
        time.sleep(random.randint(1,3))
        print('%s is piao end' % self.name)

if __name__ == '__main__':
    t=Mythread()
    t.start()
    print('主')

  

posted @ 2018-06-12 15:10  cyh追梦寻  阅读(131)  评论(0)    收藏  举报