#!/usr/bin/env python
#-*-Coding:utf-8-*-
Import threading, Time
#新线程执行的代码:
def loop ():
Print (' thread%s is running ... '% threading.current_thread (). Name)
n = 0
While n < 5:
n = n + 1
Print (' thread%s '% Threading.current_thread (). Name)
Time.sleep (3)
Print (' thread%s ended. '% Threading.current_thread (). Name)
Print (' thread%s is running ... '% threading.current_thread (). Name)
t = Threading. Thread (Target=loop, name= ' Loopthread ')
T.start ()
#t. Join ()
Print (' thread%s ended. '% Threading.current_thread (). Name)
Execution Result:
Thread Mainthread is running ...
Thread Loopthread is Running...thread Mainthread ended.
Thread Loopthread
Thread Loopthread
Thread Loopthread
Thread Loopthread
Thread Loopthread
Thread Loopthread ended.
Child threads are created in the main thread, and the main thread and child threads run in parallel
#!/usr/bin/env python
#-*-Coding:utf-8-*-
Import Queue
Import time
Import threading
Import Random
def go (name):
# Time.sleep (1)
Print ("Go" + str (name))
Time.sleep (1)
For j in Range (20):
T1 = Threading. Thread (Group=none, Target=go, Name=none, Args= (J,))
T1.start ()
For I in range (20):
Go (i)
J is parallel execution, the main thread and 20 sub-lines are executed in parallel
I is serial execution, only the main thread
#!/usr/bin/env python
#-*-Coding:utf-8-*-
Import Queue
Import time
Import threading
Import Random
Q = Queue.queue ()
def Pro (name):
Print ("---Pro Data Kaiqi")
#time. Sleep (3)
For I in range (20):
Time.sleep (1)
Print (name + "Pro Data" + str (i))
Q.put (i)
Def CON (name):
Print ("-----con data Kaiqi")
n = 0
While N < 20:
Time.sleep (3)
data = Q.get ()
Print (name + "Con data----" + str (data))
n + = 1
T1 = Threading. Thread (Group=none, Target=pro, Name=none, kwargs={' name ': ' Laoban '})
T2 = Threading. Thread (Group=none, Target=con, Name=none, kwargs={' name ': ' Yuangong '})
T1.start ()
T2.start ()
Two threads interact in parallel, taking data in one queue
This article is from the "Big Barren Sutra" blog, please be sure to keep this source http://2892931976.blog.51cto.com/5396534/1759283
The threading in Python