Creating Threads
The format is as follows
Copy the Code code as follows:
Threading. Thread (Group=none, Target=none, Name=none, args= (), kwargs={})
This constructor must be called with the keyword argument
-Group Thread groups
-Target Execution method
-Name thread names
-Tuple parameters executed by the args target
-Dictionary parameters executed by Kwargs target
Thread Object functions
Function description
Start () starts the execution of the thread
Run () A function that defines the functionality of the thread (typically overridden by a quilt class)
The Join (Timeout=none) program hangs until the thread ends, and if timeout is given, it blocks timeout seconds
GetName () returns the name of the thread
SetName (name) sets the name of the thread
The IsAlive () Boolean flag that indicates whether the thread is still running
Isdaemon () returns the daemon flag of the thread
Setdaemon (daemonic) sets the daemon flag of the thread to Daemonic (be sure to call before the start () function is called)
Common examples
Format
Copy the Code code as follows:
Import threading
def run (*arg, **karg):
Pass
Thread = Threading. Thread (target = run, name = "Default", args = (), Kwargs = {})
Thread.Start ()
Instance
Copy CodeThe code is as follows:
#!/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"
Output
Copy CodeThe code is as follows:
Sing start: (' Raise Me Up ',)
Dance Start: (' Rup ',)
Sing stop
Dance Stop
Game Over