码迷,mamicode.com
首页 > 编程语言 > 详细

python多线程

时间:2015-08-21 00:00:36      阅读:644      评论:0      收藏:0      [点我收藏+]

标签:

#!/usr/bin/python
# coding:utf-8

import threading
from time import ctime,sleep
		
class music(threading.Thread):
	def __init__(self, music_name):
		threading.Thread.__init__(self)
		self.music_name = music_name

	def run(self):
		for i in range(5):
			print "I was listening to %s. %s" %(self.music_name, ctime())
			sleep(1)
			
class movie(threading.Thread):
	def __init__(self, movie_name):
		threading.Thread.__init__(self)
		self.movie_name = movie_name

	def run(self):
		for i in range(5):
			print "I was listening to %s. %s" %(self.movie_name, ctime())
			sleep(1)



def test():
	threads = []
	
	thread1 = music(u‘爱情买卖‘)
	threads.append(thread1)
	thread2 = movie(u‘阿凡达‘)
	threads.append(thread2)
	
	for t in threads:
		#t.setDaemon(True)	#设置Daemon表示的是子线程会随着主线程一起结束,而不是等待子线程结束
		t.start()
		
	t.join()	#设置join表示主线程需要等待子线程结束了才会结束
		
	print "all over %s" %ctime()

if __name__ == ‘__main__‘:
	test()

 

threading.Thread类的使用:

1,在自己的线程类的__init__里调用threading.Thread.__init__(self, name = threadname)

Threadname为线程的名字

2, run(),通常需要重写,编写代码实现做需要的功能。

3,getName(),获得线程对象名称

4,setName(),设置线程对象名称

5,start(),启动线程

6,jion([timeout]),等待另一线程结束后再运行。

7,setDaemon(bool),设置子线程是否随主线程一起结束,必须在start()之前调用。默认为False。

8,isDaemon(),判断线程是否随主线程一起结束。

9,isAlive(),检查线程是否在运行中。

 

Thread Objects

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.

There is the possibility that “dummy thread objects” are created. These are thread objects corresponding to “alien threads”, which are threads of control started outside the threading module, such as directly from C code.  Dummy thread objects have limited functionality; they are always considered alive and daemonic, and cannot be join()ed.  They are never deleted, since it is impossible to detect the termination of alien threads.

class threading.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.

When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). As join() always returns None, you must call isAlive() after join() to decide whether a timeout happened – if the thread is still alive, the join() call timed out.

When the timeout argument is not present or None, the operation will block until the thread terminates.

A thread can be join()ed many times.

join() raises a RuntimeError if an attempt is made to join the current thread as that would cause a deadlock. It is also an error to join() a thread before it has been started and attempts to do so raises the same exception.

name

A string used for identification purposes only. It has no semantics. Multiple threads may be given the same name.  The initial name is set by the constructor.

New in version 2.6.

getName()
setName()

Pre-2.6 API for name.

ident

The ‘thread identifier’ of this thread or None if the thread has not been started.  This is a nonzero integer.  See the thread.get_ident() function.  Thread identifiers may be recycled when a thread exits and another thread is created.  The identifier is available even after the thread has exited.

New in version 2.6.

is_alive()
isAlive()

Return whether the thread is alive.

This method returns True just before the run() method starts until just after the run() method terminates.  The module function enumerate() returns a list of all alive threads.

Changed in version 2.6: Added is_alive() spelling.

daemon

A boolean value indicating whether this thread is a daemon thread (True) or not (False).  This must be set before start() is called, otherwise RuntimeError is raised.  Its initial value is inherited from the creating thread; the main thread is not a daemon thread and therefore all threads created in the main thread default to daemon = False.

The entire Python program exits when no alive non-daemon threads are left.

New in version 2.6.

isDaemon()
setDaemon()

Pre-2.6 API for daemon.

python多线程

标签:

原文地址:http://www.cnblogs.com/hushaojun/p/4746478.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!