Python多线程

1.继承Thread类

#! /usr/bin/python
# -*- coding: utf-8 -*-
import threading
class MyThread(threading.Thread):
def __init__(self, name=None):
threading.Thread.__init__(self)
self.name = name
def run(self):
print self.name
def test():
for i in range(0, 100):
t = MyThread("thread_" + str(i))
t.start()
if __name__=='__main__':
test()

一定实现init和run方法。

2.使用 start_new_thread 方法开启线程

#! /usr/bin/python
# -*- coding: utf-8 -*-
import threading
class MyThread(threading.Thread):
def __init__(self,name=None):
threading.Thread.__init__(self)
self.name = name
def run(self):
print self.name
def test():
for i in range(0,10):
t = MyThread("thread_" + str(i))
t.start()
if __name__=="__main__":
test()
import time, thread
def timer():
print('hello')
def test():
for i in range(0, 10):
thread.start_new_thread(timer, ())
if __name__=='__main__':
test()
time.sleep(2)

 

你可能感兴趣的:(thread,多线程,python,import)