python threading模块、Thread类讲解

threading模块

This module constructs higher-level threading interfaces on top of the lower level thread module.

threading模块提供的类:

Thread, Lock, Rlock, Condition, [Bounded]Semaphore, Event, Timer, local.

Thread类

This class represents an activity that is run in a separate thread of control. There are two ways to specify the activity: by passing a callable object to the constructor, or by overriding the run() method in a subclass. No other methods (except for the constructor) should be overridden in a subclass. In other words, only override the init() and run() methods of this class.

Once a thread object is created, its activity must be started by calling the thread’s start() method. This invokes the run() method in a separate thread of control.

Once the thread’s activity is started, the thread is considered ‘alive’. It stops being alive when its run() method terminates – either normally, or by raising an unhandled exception. The is_alive() method tests whether the thread is alive.

Other threads can call a thread’s join() method. This blocks the calling thread until the thread whose join() method is called is terminated.

A thread has a name. The name can be passed to the constructor, and read or changed through the name attribute.

A thread can be flagged as a “daemon thread”. The significance of this flag is that the entire Python program exits when only daemon threads are left. The initial value is inherited from the creating thread. The flag can be set through the daemon property.

Note: Daemon threads are abruptly stopped at shutdown. Their resources (such as open files, database transactions, etc.) may not be released properly. If you want your threads to stop gracefully, make them non-daemonic and use a suitable signalling mechanism such as an Event.

There is a “main thread” object; this corresponds to the initial thread of control in the Python program. It is not a daemon thread.
直接一点就是,有两种方式创建线程对象:
1、调用Thread类构造函数,并传入一个可调用的方法
2、直接继承Thread类,然后重写父类的__init__方法和run方法

演示::通过Thread类创建线程对象

# coding:gbk

import threading
import time

def action():
    print '当前线程的名字是'.decode('gbk')+threading.current_thread().getName()
    time.sleep(1)

if __name__ == '__main__':
    print '当前线程的名字是'.decode('gbk') + threading.current_thread().getName()

    t=threading.Thread(target=action,args=())  # 通过Thread类创建线程对象

    t.start()

    t.join()

    print 'all over.'

执行结果:

C:\Python27\python.exe E:/pythonproj/基础练习/t1.py
当前线程的名字是MainThread
当前线程的名字是Thread-1
all over.

Process finished with exit code 0

演示:继承Thread类,并重写run方法

# coding:gbk

import threading
import time

class MyThread(threading.Thread):
    def __init__(self): #重写构造方法
        threading.Thread.__init__(self)  #调用父类构造方法进行初始化
        self.name='myFirstThread'

    def run(self): #重写run方法
        print '当前线程的名字:'.decode('gbk')+self.getName()
        time.sleep(1)


if __name__=='__main__':
    print '当前线程的名字:'.decode('gbk') + threading.currentThread().getName()

    mt=MyThread()

    mt.start()

    mt.join()

    print 'all over.'

构造方法
Thread(group=None, target=None, name=None, args=(), kwargs={})

This constructor should always be called with keyword arguments. Arguments are:

group should be None; reserved for future extension when a ThreadGroup class is implemented.

target is the callable object to be invoked by the run() method. Defaults to None, meaning nothing is called.

name is the thread name. By default, a unique name is constructed of the form “Thread-N” where N is a small decimal number.

args is the argument tuple for the target invocation. Defaults to ().

kwargs is a dictionary of keyword arguments for the target invocation. Defaults to {}.

If the subclass overrides the constructor, it must make sure to invoke the base class constructor (Thread.init()) before doing anything else to the thread.

实例方法

  • start():

Start the thread’s activity.

It must be called at most once per thread object. It arranges for the object’s run() method to be invoked in a separate thread of control.

This method will raise a RuntimeError if called more than once on the same thread object.

  • run()

Method representing the thread’s activity.

You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.

  • join([timeout])

Wait until the thread terminates. This blocks the calling thread until the thread whose join() method is called terminates – either normally or through an unhandled exception – or until the optional timeout occurs.

  • getName()/setName()

获取和设置线程的名字

  • isAlive()

Return whether the thread is alive.

  • isDaemon()/setDaemon()

获取/设置是后台线程
如果是后台线程,主线程执行过程中,后台线程也在进行,主线程执行完毕后,后台线程不论成功与否,主线程和后台线程均停止。
如果是前台线程,主线程执行过程中,前台线程也在进行,主线程执行完毕后,等待前台线程也执行完成后,程序停止。

演示:程序中存在前台线程,主线程退出,整个进程不退出,直到前台线程结束

# coding:gbk

import threading
import time

def action(arg):
    time.sleep(1)
    print 'sub thread starts! the thread name is %s\n' % threading.currentThread().getName()
    print 'the argument is %s\n' % arg
    time.sleep(30)
    print 'sub thread ends!\n'


if __name__ == '__main__':
    for i in xrange(1,5):
        t=threading.Thread(target=action,args=(i,))//由于主线程不是守护线程,那么它创建的线程默认也是非守护线程
        t.start()

    print 'main thread ends\n'

执行结果:

C:\Python27\python.exe E:/pythonproj/基础练习/t3.py
main thread ends

sub thread starts! the thread name is Thread-1

the argument is 1

sub thread starts! the thread name is Thread-4
sub thread starts! the thread name is Thread-3


sub thread starts! the thread name is Thread-2
the argument is 4
the argument is 3



the argument is 2

sub thread ends!

sub thread ends!
sub thread ends!
sub thread ends!




Process finished with exit code 0

演示:程序中存在后台线程,主线程退出,那么后台线程也就退出,整个进程退出

# coding:gbk

import threading
import time

def action(arg):
    time.sleep(1)
    print 'sub thread starts! the thread name is %s\n' % threading.currentThread().getName()
    print 'the argument is %s\n' % arg
    time.sleep(30)
    print 'sub thread ends!\n'


if __name__ == '__main__':
    for i in xrange(1,5):
        t=threading.Thread(target=action,args=(i,))
        t.setDaemon(True) #设置为后台线程
        t.start()

    print 'main thread ends\n'

执行结果:

C:\Python27\python.exe E:/pythonproj/基础练习/t3.py
main thread ends


Process finished with exit code 0

从上面的执行结果可以看出,主线程退出,程序马上结束。

演示:通过调用join方法,循环等待各个子线程结束

# coding:gbk

import threading
import time

def action(arg):
    time.sleep(1)
    print 'sub thread starts! the thread name is %s\n' % threading.currentThread().getName()
    print 'the argument is %s\n' % arg
    time.sleep(1)
    print 'sub thread ends!\n'


if __name__ == '__main__':
    threads=[]
    for i in xrange(1,5):
        t=threading.Thread(target=action,args=(i,))
        threads.append(t)
        t.setDaemon(True) #设置为后台线程
        t.start()

    for t in threads: #循环等待各个子线程结束
        t.join()

    print 'main thread ends\n'

执行结果:

C:\Python27\python.exe E:/pythonproj/基础练习/t3.py
sub thread starts! the thread name is Thread-2
sub thread starts! the thread name is Thread-1


the argument is 2
the argument is 1


sub thread starts! the thread name is Thread-4
sub thread starts! the thread name is Thread-3


the argument is 4
the argument is 3


sub thread ends!
sub thread ends!


sub thread ends!
sub thread ends!


main thread ends


Process finished with exit code 0

从上面的执行可以看出,主线程会依次等待各个子线程结束,然后再退出。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

历史五千年

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值