Python线程的用法 函数式线程_thread和threading 样例
函数式线程写起来比较简单,但是功能没有threading那么高级,先来个函数式编程样例:
#!/usr/bin/python #coding: utf-8 #————————————————————————函数式线程———————————————————————————————————————— #QQ496631085 小和 XiaoHe import _thread import time def print_time(threadName,delay): count = 0 while count<4: time.sleep(delay) count += 1 print(threadName,time.ctime()) print(time.ctime())#打印现在时间以方便对比 _thread.start_new_thread(print_time,("thread-1",2)) _thread.start_new_thread(print_time,("thread-2",4)) time.sleep(200)#不加这个有的编译器,直接到最后就停止整个程序运行了,看不出效果 print("end") #————————————————————————函数式线程————————————————————————————————————————
然后就是threading线程样例:
#!/usr/bin/python #coding: utf-8 #===========================threading======================================== #QQ496631085 XiaoHe import threading import time class myThread(threading.Thread): """docstring for myThread""" def __init__(self, name,delay): threading.Thread.__init__(self) print(name+"线程开始时间" +time.ctime()) self.name =name self.delay = delay def run(self): print("Starting " + self.name + time.ctime()) print_time(self.name, self.delay) print("Exiting " + self.name + time.ctime()) def print_time(threadName, delay): counter = 0 while counter < 3: time.sleep(delay) print("延时" + threadName ,time.ctime()) counter+=1 threads =[] #创建新线程 thread1= myThread("Thread-111",2) thread2= myThread("Thread-222",4) #开始新线程 thread1.start() thread2.start() #添加线程到线程列表 然后一直等待线程终止 threads.append(thread1) threads.append(thread2) #等待线程结束 for t in threads: t.join() print("线程结束") #===========================threading========================================
如果觉得这个还慢有不足的地方,可以试试queue的多线程爬虫