zoukankan      html  css  js  c++  java
  • python学习之多线程编程

    多线程有点类似于多个程序同时运行。

    其有以下优点:

    • 使用线程可以把占据长时间的程序中的任务放到后台去处理。
    • 程序的运行速度可能加快。
    • 在一些等待的任务实现上如用户输入、文件读写和网络收发数据等,线程就比较有用了。在这种情况下我们可以释放一些珍贵的资源如内存占用等等。

    下面是学习的代码。一些关键的点在注释里标出:

    import threading
    import time
    list = [0,0,0,0,0,0,0,0,0,0,0,0]
    class myThread(threading.Thread):
        def __init__(self,threadId,name,counter):
            threading.Thread.__init__(self)
            self.threadId = threadId
            self.name = name
            self.counter = counter
        def run(self):
            print ("开始线程:",self.name)
            # 获得锁,成功获得锁定后返回 True
            # 可选的timeout参数不填时将一直阻塞直到获得锁定
            # 否则超时后将返回 False
            threadLock.acquire()
            print_time(self.name,self.counter,list.__len__())
            # 释放锁
            threadLock.release()
        def __del__(self):
            print (self.name,"线程结束!")
    def print_time(threadName,delay,counter):
        while counter:
            time.sleep(delay)
            list[counter-1] += 1
            print ("[%s] %s 修改第 %d 个值,修改后值为:%d" % (time.ctime(time.time()),threadName,counter,list[counter-1]))
            counter -= 1
    threadLock = threading.Lock()
    threads = []
    # 创建新线程
    thread1 = myThread(1,"Thread-1",1)
    thread2 = myThread(2,"Thread-2",2)
    # 开启新线程
    thread1.start()
    thread2.start()
    # 添加线程到线程列表
    threads.append(thread1)
    threads.append(thread2)
    # 等待所有线程完成
    for t in threads:
        t.join()
    print ("主进程结束!")

    运行结果如下:

    参考网站:菜鸟教程 https://www.runoob.com/python/python-multithreading.html  一个很好计算机技术的基础网站,涉及的范围很广。

    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文链接,否则保留追究法律责任的权利。
  • 相关阅读:
    ABP 往前端返回详细的错误信息
    ABP 报错1
    three.js 测试1
    three.js 添加 图形控制界面 gui
    three.js 设置透明度
    three.js 基础使用1
    three.js 添加环境光
    three.js 添加三维坐标系
    P2690 接苹果
    [USACO08FEB]修路Making the Grade
  • 原文地址:https://www.cnblogs.com/ManbaDF99/p/12755164.html
Copyright © 2011-2022 走看看