简单创建多线程

0. 导入多线程模块

import threading

1. 方法开启多线程

先将执行操作定义到方法内部

def test(name):
    for value in range(5):
        print('thread:{}\tcount:{}'.format(name,value))


多线程开启方法执行

threading._start_new_thread(test,('one',))
threading._start_new_thread(test,('two',))
threading._start_new_thread(test,('three',))

注意:括号两个参数,第一个是方法对象,第二个是参数元组

当元组内部只有一个元素时,后面需要添加逗号,和小括号进行区分

执行结果

thread:one	count:0
thread:three	count:0
thread:two	count:0
thread:one	count:1
thread:three	count:1
thread:two	count:1
thread:one	count:2
thread:three	count:2
thread:two	count:2
thread:one	count:3
thread:three	count:3
thread:two	count:3
thread:one	count:4
thread:three	count:4
thread:two	count:4

注意:当程序主线程执行完毕,子线程会被终止,所以需要让主线程睡一会(目前我的程度只能这样)


import time

time.sleep(2)

线程对象

和普通对象区别在于两点

0. 类:继承threading.Thread对象

1. 方法:

__init__:初始化方法必须调用父类方法初始化,才能进行本类初始化操作,父类初始化不带外参

run:开启线程操作主要完成的操作语句在此定义

2. 调用:start准备,后续自动调用,遵循线程生命周期

import threading
import time

class MyHead(threading.Thread):

    def __init__(self,name):
        super(MyHead, self).__init__()
        self.name = name

    def run(self):
        for value in range(5):
            print('thread:{}\tcount:{}'.format(self.name,value))

thread1 = MyHead('one')
thread2 = MyHead('two')

thread1.start()
thread2.start()

线程对象会自动自行完毕,再关闭主线程,无需sleep

结果:

thread:one	count:0
thread:one	count:1
thread:one	count:2
thread:two	count:0
thread:one	count:3
thread:one	count:4
thread:two	count:1
thread:two	count:2
thread:two	count:3
thread:two	count:4


相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页