There are two ways to implement multithreading in python: one is to generate new threads through functions, and the other is to implement multithreading through object-oriented methods.
Call the start_new_thread () function in the thread module to generate a new thread.
#! /Usr/bin/env python # encoding: UTF-8 # author: zhxiaimport threadimport timethread_count = 0; def test (num, interval): for x in xrange ): print 'current thread is: % d, and x is: % d' % (num, x) time. sleep (interval) thread. exit_thread () if _ name __= = '_ main _': thread. start_new_thread (test, (1, 1) thread. start_new_thread (test, (2, 1) thread. start_new_thread (test, (3, 1) # To prevent the main thread from exiting before the sub-thread, you need to check the current number of sub-threads until all sub-threads have completed execution. sleep (0.001) # sleep is required. Otherwise, the number of sub-threads cannot be obtained. _ count ()> 0: time. sleep (0.5)
Implemented through the threading module:
#!/usr/bin/env python#encoding:utf-8#author:zhxiaimport timeimport threadingimport sysclass test(threading.Thread): def __init__(self,num,interval): threading.Thread.__init__(self) self.thread_num=num self.interval=interval def run(self): for x in xrange(1,9): print 'current thread is %d,and x is %d'%(self.thread_num,x) time.sleep(self.interval)if __name__=='__main__': t1=test(1,1) t2=test(2,1) t3=test(3,1) t1.start(); t2.start(); t3.start();