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  一个很好计算机技术的基础网站,涉及的范围很广。

猜你喜欢

转载自www.cnblogs.com/ManbaDF99/p/12755164.html