创建线程的方式-threading中的Thread类

创建多线程

from threading import Thread
import time,os

def task():
    print('%s is running' %os.getpid())#os.getpid()进程id
    time.sleep(5)
    print('%s is done' %os.getpid())

if __name__ == '__main__':
    t=Thread(target=task,)#函数名,元组式的参数
    t.start()

    print('')
#运行结果
#580 is running
#
#580 is done
#开启子线程和开启子进程方法都是一样的,只是导入的模块不同
#使用子进程执行上面的代码会先打印“主”
#而使用子线程会先打印“580 is running”说明了开启线程是比开启进程要快的

开启线程同样可以使用继承类

class Mythread(Thread):
    def __init__(self):
        super().__init__()

    def run(self):
        print('%s is running' % os.getpid())
        time.sleep(5)
        print('%s is done' % os.getpid())



if __name__ == '__main__':
    t=Mythread()
    t.start()
其他方法
#current_thread()返回进程信息,current_thread().getName() #返回进程名字
#enumerate # 查看当前进程
# active_count # 查看进程数
#这些都要从threadind中导入
#多线程中也有start(),jion()

from threading import Thread,current_thread,enumerate,active_count
import time

def task():
    print('%s is running' %current_thread().ident)
    time.sleep(5)
    print('%s is done' %current_thread().getName())


if __name__ == '__main__':
    t=Thread(target=task,name='xxxx') #可以为进程指定名字不指定默认从Thread-1开始
    t.start()


    #查看当前活着的线程
    print(enumerate()) #返回活着进程信息的列表
    print(active_count())
    print('',current_thread().getName())
#运行结果
#xxxx is running
#[<_MainThread(MainThread, started 11784)>, <Thread(xxxx, started 5700)>]
#2
#主 MainThread
#xxxx is done

 

 

posted @ 2017-12-01 19:16  瓜田月夜  阅读(155)  评论(0)    收藏  举报