demo1
#!/usr/bin/python # -*- coding: UTF-8 -*- import time from threading import Thread # 自定义线程函数。 def main(name="Python"): for i in range(2): print("hello", name) time.sleep(1) # 创建线程01,不指定参数 thread_01 = Thread(target=main) # 启动线程01 thread_01.start() # 创建线程02,指定参数,注意逗号 thread_02 = Thread(target=main, args=("MING",)) # 启动线程02 thread_02.start()
demo2
#!/usr/bin/python # -*- coding: UTF-8 -*- import time from threading import Thread class MyThread(Thread): def __init__(self, name="Python"): # 注意,super().__init__() 一定要写 # 而且要写在最前面,否则会报错。 super().__init__() self.name=name def run(self): for i in range(2): print("hello", self.name) time.sleep(1) if __name__ == '__main__': # 创建线程01,不指定参数 thread_01 = MyThread() # 创建线程02,指定参数 thread_02 = MyThread("MING") thread_01.start() thread_02.start()
demo3
#!/usr/bin/python # -*- coding: UTF-8 -*- import threading import time exitFlag = 0 class myThread (threading.Thread): #继承父类threading.Thread def __init__(self, threadID, name, counter): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter def run(self): #把要执行的代码写到run函数里面 线程在创建后会直接运行run函数 print "Starting " + self.name print_time(self.name, self.counter, 5) print "Exiting " + self.name def print_time(threadName, delay, counter): while counter: if exitFlag: (threading.Thread).exit() time.sleep(delay) print "%s: %s" % (threadName, time.ctime(time.time())) counter -= 1 # 创建新线程 thread1 = myThread(1, "Thread-1", 1) thread2 = myThread(2, "Thread-2", 2) # 开启线程 thread1.start() thread2.start() print "Exiting Main Thread"
参考:
https://www.cnblogs.com/wongbingming/p/9028851.html
https://www.runoob.com/python/python-multithreading.html