Python中的线程使用

1. 海外社媒客户开发工具【免费】了,帮你从GG/FB/Ins/谷歌地图上免费获取客户

2. WhatsApp 聊天记录保险【99元/年】,聊天记录不怕丢。自带翻译、多开,号码抓取、群发

3. 外贸网站搭建、谷歌SEO、社媒运营、企业WhatsApp管理、外贸管理软件、AI应用,【联系我】

Python中使用线程有两种方式:函数或者用类来包装线程对象。

1、  函数式:调用thread模块中的start_new_thread()函数来产生新线程。如下例:

  1. import time
  2. import thread
  3. def timer(no, interval):
  4.     cnt = 0
  5.     while cnt<10:
  6.         print ‘Thread:(%d) Time:%s/n’%(no, time.ctime())
  7.         time.sleep(interval)
  8.         cnt+=1
  9.     thread.exit_thread()
  10. def test(): #Use thread.start_new_thread() to create 2 new threads
  11.     thread.start_new_thread(timer, (1,1))
  12.     thread.start_new_thread(timer, (2,2))
  13. if __name__==’__main__’:
  14.     test()

 

上面的例子定义了一个线程函数timer,它打印出10条时间记录后退出,每次打印的间隔由interval参数决定。thread.start_new_thread(function, args[, kwargs])的第一个参数是线程函数(本例中的timer方法),第二个参数是传递给线程函数的参数,它必须是tuple类型,kwargs是可选参数。

线程的结束可以等待线程自然结束,也可以在线程函数中调用thread.exit()或thread.exit_thread()方法。

2、  创建threading.Thread的子类来包装一个线程对象,如下例:

  1. import threading
  2. import time
  3. class timer(threading.Thread): #The timer class is derived from the class threading.Thread
  4.     def __init__(self, num, interval):
  5.         threading.Thread.__init__(self)
  6.         self.thread_num = num
  7.         self.interval = interval
  8.         self.thread_stop = False
  9.     def run(self): #Overwrite run() method, put what you want the thread do here
  10.         while not self.thread_stop:
  11.             print ‘Thread Object(%d), Time:%s/n’ %(self.thread_num, time.ctime())
  12.             time.sleep(self.interval)
  13.     def stop(self):
  14.         self.thread_stop = True
  15. def test():
  16.     thread1 = timer(1, 1)
  17.     thread2 = timer(2, 2)
  18.     thread1.start()
  19.     thread2.start()
  20.     time.sleep(10)
  21.     thread1.stop()
  22.     thread2.stop()
  23.     return
  24. if __name__ == ‘__main__’:
  25.     test()

1. 海外社媒客户开发工具【免费】了,帮你从GG/FB/Ins/谷歌地图上免费获取客户

2. WhatsApp 聊天记录保险【99元/年】,聊天记录不怕丢。自带翻译、多开,号码抓取、群发

3. 外贸网站搭建、谷歌SEO、社媒运营、企业WhatsApp管理、外贸管理软件、AI应用,【联系我】

微信扫一扫 或 点击链接联系我

仍有疑问,点击 链接,加个 微信 好友,一起交流。

发表评论