zoukankan      html  css  js  c++  java
  • Python 创建线程的方法

    • 使用的是 threading 模块

    • 代码如下:

          1 #!/usr/bin/python3
          2
          3 import threading
          4 import time
          5
          6 exitFlag = 0
          7        // 创建线程的类
          8 class myThead (threading.Thread):
          9     def __init__(self, threadID, name, counter):
         10         threading.Thread.__init__(self)
         11         self.threadID = threadID
         12         self.name = name
         13         self.counter = counter
         14     def run(self):
         15         threadLock.acquire();    // 线程同步
         16         print("start function : "+ self.name)
         17         print_time(self.name, self.counter, 5)
         18         print("exit function :" + self.name)
         19         threadLock.release()    // 线程同步释放
         20
         21       // 线程调用的函数
         22 def print_time(threadName, delay, counter):
         23     while counter:
         24         if exitFlag:
         25             threadName.exit()
         26         time.sleep(delay)
         27         print ("%s : %s" % (threadName, time.ctime(time.time())))
         28         counter -= 1
         29
         30 threadLock = threading.Lock()
         31 threads = []
         32
         33 thread1 = myThead(1, "Thread-1", 1);    // 创建线程的实体
         34 thread2 = myThead(2, "Thread-2", 2);
         35 thread3 = myThead(3, "Thread-3", 3);
         36
         37 thread1.start()
         38 thread2.start()
         39 thread3.start()
         40
         41 threads.append(thread1);    // 加入线程数组
         42 threads.append(thread2);
         43 threads.append(thread3);
         44
         45 for t in threads:
         46     t.join();    // 线程执行
         47
         48 print("exit main process");
         49
    
  • 相关阅读:
    小端字节序与大端字节序
    V8引擎的垃圾回收策略
    TTL 和 DNS TTL 的区别
    详解 undefined 与 null 的区别
    Node.js 事件循环机制
    requestAnimationFrame 知多少?
    Web前端知识体系精简
    Vue.js 和 MVVM 小细节
    使用 Node.js 搭建 Web 服务器
    H5单页面手势滑屏切换原理
  • 原文地址:https://www.cnblogs.com/chenfulin5/p/8927079.html
Copyright © 2011-2022 走看看