start.py code is as below.
import threading
class myThread(threading.Thread):
def __init__(self, threadID, name):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
def run(self):
currentThreadname = threading.currentThread()
print "running in ", currentThreadname
thread = myThread(1,"mythrd")
thread.start()
Start it with python for two times.
python start.py
running in <myThread(mythrd, started 140461133485824)>
python start.py
running in <myThread(mythrd, started 140122860668672)>
run.py code is as below.
import threading
class myThread(threading.Thread):
def __init__(self, threadID, name):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
def run(self):
currentThreadname = threading.currentThread()
print "running in ", currentThreadname
thread = myThread(1,"mythrd")
thread.run()
run.py is only one line different from start.py.
Now start run.py for two times.
python run.py
running in <_MainThread(MainThread, started 139854546364160)>
python run.py
running in <_MainThread(MainThread, started 139854546364160)>
startandrun.py code is as below.
class myThread(threading.Thread):
def __init__(self, threadID, name):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
def run(self):
currentThreadname = threading.currentThread()
print "running in ", currentThreadname
thread = myThread(1,"mythrd")
thread.start()
thread.run()
Now start startandrun.py for two times also.
python startandrun.py
running in <myThread(mythrd, started 140317119899392)>
running in <_MainThread(MainThread, started 140317144454912)>
python startandrun.py
running in running in <_MainThread(MainThread, started 139980210505472)>
<myThread(mythrd, started 139980185949952)>
As JohanL say:
When running two separate threads, all bets are off as to which will execute first.
You are basically leaving the scheduling to the operating system.
The first time to execute startandrun.py, thread.start()
was executed before thread.run()
,it result in the output:
running in <myThread(mythrd, started 140317119899392)>
running in <_MainThread(MainThread, started 140317144454912)>
The second time to execute startandrun.py, thread.start()
was executed after thread.run()
,why not result in the output:
running in <_MainThread(MainThread, started 140317144454912)>
running in <myThread(mythrd, started 140317119899392)>
instead of
running in running in <_MainThread(MainThread, started 139980210505472)>
<myThread(mythrd, started 139980185949952)>