Python多线程编程简单介绍

yipeiwu_com6年前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

相关文章

树莓派中python获取GY-85九轴模块信息示例

树莓派中python获取GY-85九轴模块信息示例

先看效果图 GY-85.py: 复制代码 代码如下:#!/usr/bin/python3# -*- coding: utf-8 -*-import cursesfrom t...

Python操作MongoDB数据库PyMongo库使用方法

引用PyMongo 复制代码 代码如下: >>> import pymongo 创建连接Connection 复制代码 代码如下: >>> impo...

Python操作Oracle数据库的简单方法和封装类实例

本文实例讲述了Python操作Oracle数据库的简单方法和封装类。分享给大家供大家参考,具体如下: 最近工作有接触到Oracle,发现很多地方用Python脚本去做的话,应该会方便很多...

使用PyInstaller将python转成可执行文件exe笔记

1、安装PyInstaller PyInstaller的作用如标题所说,首先需要下载PyInstaller和UPX,UPX是用来压缩exe的,点击超链接下载吧,目前稳定版本是1.3,注意...

Python面向对象程序设计之继承与多继承用法分析

本文实例讲述了Python面向对象程序设计之继承与多继承。分享给大家供大家参考,具体如下: 1. 继承 在C++和Java中,使用继承时,子类的构造函数会自动调用父类的构造函数,但在Py...