• start 运行函数
  • run 定义函数 ```python import threading # python3 主要用这个

def my_thread(arg1, arg2): name = threading.current_thread().getName() print(‘%s %s %s’ % (name, arg1, arg2))

for i in range(1, 100, 2):

  1. # 创建线程
  2. t1 = threading.Thread(target=my_thread, args=(i, i+1))
  3. t1.start()

输出

Thread-1 1 2 Thread-2 3 4Thread-3 5 6

Thread-4 7 8 Thread-5 9 10 Thread-6 11 12 Thread-7 13 14 Thread-8 15 16 Thread-9 17 18 Thread-10 19 20 Thread-11 21 22 Thread-12 23 24 Thread-13 25 26Thread-14 27 28

Thread-15 29 30 Thread-16 31 32 Thread-17 33 34 Thread-18 35 36 Thread-19 37 38 Thread-20 39 40 Thread-21 41 42 Thread-22 43 44 Thread-23 45 46 Thread-24 47 48 Thread-25 49 50 Thread-26 51 52 Thread-27 53 54 Thread-28 55 56 Thread-29 57 58 Thread-30 59 60 Thread-31 61 62Thread-32 63 64

Thread-33 65 66 Thread-34 67 68 Thread-35 69 70Thread-36 71 72

Thread-37 73 74 Thread-38 75 76 Thread-39 77 78 Thread-40 79 80 Thread-41 81 82 Thread-42 83 84 Thread-43 85 86 Thread-44 87 88 Thread-45 89 90 Thread-46 91 92 Thread-47 93 94 Thread-48 95 96 Thread-49 97 98 Thread-50 99 100

  1. <a name="XDTwl"></a>
  2. # 同步
  3. ```python
  4. import threading # python3 主要用这个
  5. class MyThread(threading.Thread):
  6. def run(self):
  7. print(threading.current_thread().getName(), 'start')
  8. print('run')
  9. print(threading.current_thread().getName(), 'stop')
  10. t1 = MyThread()
  11. t1.start()
  12. t1.join() # 主线程等待
  13. print(threading.current_thread().getName(), 'end')
  14. # 输出
  15. Thread-1 start
  16. run
  17. Thread-1 stop
  18. MainThread end

生产者/消费者问题