Objective:
The above is a single thread, now will be a multi-threaded, directly on the code:
1. Create a threading. A subclass of thread to wrap a thread object
#encoding: UTF8
Import threading
Import time
Class Timer (threading. Thread):
def __init__ (Self,num,interval):
Threading. Thread.__init__ (self)
#设置产生线程的个数
Self.thread_num = num
#产生线程的相隔时间
Self.interval = Interval
Self.thread_stop = False
def run (self):
While not self.thread_stop:
print ' Thread Object (%d), time:%s\n '% (Self.thread_num,time.ctime ())
Time.sleep (Self.interval)
def stop (self):
Self.thread_stop = True
def test ():
Thread1 = timer (up to)
Thread2 = Timer (2,2)
Thread1.start ()
Thread2.start ()
Time.sleep (10)
Thread1.stop ()
Thread2.stop ()
Return
if __name__ = = ' __main__ ':
Test ()
Operation Result:
Threading. Use of the thread class:
1). Call threading in the __init__ of your own thread class. Thread.__init__ (self, name = ThreadName)
ThreadName is the name of the thread
2). Run (), which usually requires rewriting and writing code to implement the required functionality.
3). GetName (), get the Thread object name
4). SetName (), set thread object name
5). Start (), starting thread
6). Jion ([timeout]), wait for another thread to finish before running.
7). Setdaemon (bool), set whether the child thread ends with the main thread and must be called before start (). The default is False.
8). Isdaemon () to determine if the thread has ended with the main threads.
9). IsAlive () to check if the thread is running.
In addition, the threading module itself provides a number of methods and other classes that can help us better use and manage threads
I'll talk to you tomorrow.
Simple synchronization
Python Multithreading (practice)