[Python] python线程同步 →→→→→进入此内容的聊天室

来自 , 2020-12-25, 写在 Python, 查看 113 次.
URL http://www.code666.cn/view/98fb2022
  1. #!/usr/bin/python
  2.  
  3. import threading
  4. import time
  5.  
  6. class myThread (threading.Thread):
  7.     def __init__(self, threadID, name, counter):
  8.         threading.Thread.__init__(self)
  9.         self.threadID = threadID
  10.         self.name = name
  11.         self.counter = counter
  12.     def run(self):
  13.         print "Starting " + self.name
  14.         # Get lock to synchronize threads
  15.         threadLock.acquire()
  16.         print_time(self.name, self.counter, 3)
  17.         # Free lock to release next thread
  18.         threadLock.release()
  19.  
  20. def print_time(threadName, delay, counter):
  21.     while counter:
  22.         time.sleep(delay)
  23.         print "%s: %s" % (threadName, time.ctime(time.time()))
  24.         counter -= 1
  25.  
  26. threadLock = threading.Lock()
  27. threads = []
  28.  
  29. # Create new threads
  30. thread1 = myThread(1, "Thread-1", 1)
  31. thread2 = myThread(2, "Thread-2", 2)
  32.  
  33. # Start new Threads
  34. thread1.start()
  35. thread2.start()
  36.  
  37. # Add threads to thread list
  38. threads.append(thread1)
  39. threads.append(thread2)
  40.  
  41. # Wait for all threads to complete
  42. for t in threads:
  43.     t.join()
  44. print "Exiting Main Thread"
  45.  
  46.  
  47. #//python/8382

回复 "python线程同步"

这儿你可以回复上面这条便签

captcha