zoukankan      html  css  js  c++  java
  • python 多线程Thread

    demo1

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    
    import time
    from threading import Thread
    # 自定义线程函数。
    def main(name="Python"):
        for i in range(2):
            print("hello", name)
            time.sleep(1)
     
    # 创建线程01,不指定参数
    thread_01 = Thread(target=main)
    # 启动线程01
    thread_01.start()
    
    # 创建线程02,指定参数,注意逗号
    thread_02 = Thread(target=main, args=("MING",))
    # 启动线程02
    thread_02.start()

    demo2

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    import time
    from threading import Thread
    class MyThread(Thread):
        def __init__(self, name="Python"):
            # 注意,super().__init__() 一定要写
            # 而且要写在最前面,否则会报错。
            super().__init__()
            self.name=name
    
        def run(self):
            for i in range(2):
                print("hello", self.name)
                time.sleep(1)
    
    if __name__ == '__main__':
        # 创建线程01,不指定参数
        thread_01 = MyThread()
        # 创建线程02,指定参数
        thread_02 = MyThread("MING")
    
        thread_01.start()
        thread_02.start()

     demo3

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
     
    import threading
    import time
     
    exitFlag = 0
     
    class myThread (threading.Thread):   #继承父类threading.Thread
        def __init__(self, threadID, name, counter):
            threading.Thread.__init__(self)
            self.threadID = threadID
            self.name = name
            self.counter = counter
        def run(self):                   #把要执行的代码写到run函数里面 线程在创建后会直接运行run函数 
            print "Starting " + self.name
            print_time(self.name, self.counter, 5)
            print "Exiting " + self.name
     
    def print_time(threadName, delay, counter):
        while counter:
            if exitFlag:
                (threading.Thread).exit()
            time.sleep(delay)
            print "%s: %s" % (threadName, time.ctime(time.time()))
            counter -= 1
     
    # 创建新线程
    thread1 = myThread(1, "Thread-1", 1)
    thread2 = myThread(2, "Thread-2", 2)
     
    # 开启线程
    thread1.start()
    thread2.start()
     
    print "Exiting Main Thread"

    参考:
    https://www.cnblogs.com/wongbingming/p/9028851.html
    https://www.runoob.com/python/python-multithreading.html

  • 相关阅读:
    Servlet接口实现类开发步骤
    Servlet概述
    Web服务器之HTTP协议与Tomcat服务器
    vant中van-picker选项插入图片
    排序算法-插入排序
    排序算法-快速排序
    排序算法-冒泡排序
    浅谈C#中Dictionary的实现。
    设计模式(23)-备忘录模式
    设计模式(22)-访问者模式
  • 原文地址:https://www.cnblogs.com/sea-stream/p/11178904.html
Copyright © 2011-2022 走看看