Python多线程编程简介

创建线程

格式如下

threading.Thread(group=None, target=None, name=None, args=(), kwargs={})

这个构造器必须用关键字传参调用
- group 线程组
- target 执行方法
- name 线程名字
- args target执行的元组参数
- kwargs target执行的字典参数

Thread对象函数
函数描述
start()开始线程的执行
run()定义线程的功能的函数(一般会被子类重写)
join(timeout=None)程序挂起,直到线程结束;如果给了 timeout,则最多阻塞 timeout 秒
getName()返回线程的名字
setName(name)设置线程的名字
isAlive()布尔标志,表示这个线程是否还在运行中
isDaemon()返回线程的 daemon 标志
setDaemon(daemonic)把线程的 daemon 标志设为 daemonic(一定要在调用 start()函数前调用)
常用示例
  • 格式
import threading

def run(*arg, **karg):
    pass
thread = threading.Thread(target = run, name = "default", args = (), kwargs = {})
thread.start()
  • 实例
#!/usr/bin/python
#coding=utf-8

import threading
from time import ctime,sleep

def sing(*arg):
    print "sing start: ", arg
    sleep(1)
    print "sing stop"


def dance(*arg):
    print "dance start: ", arg
    sleep(1)
    print "dance stop"

threads = []

#创建线程对象
t1 = threading.Thread(target = sing, name = 'singThread', args = ('raise me up',))
threads.append(t1)

t2 = threading.Thread(target = dance, name = 'danceThread', args = ('Rup',))
threads.append(t2)

#开始线程
t1.start()
t2.start()

#等待线程结束
for t in threads:
    t.join()

print "game over"

输出

sing start:  ('raise me up',)
dance start:  ('Rup',)
sing stop
dance stop
game over
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值