python中的多线程

基本概念:

线程:进程中的每个子任务不能独立存在

进程:独立的所有子任务的集合

线程,进程:目的都是想同时完成任务

线程的五个状态:

1:创建对象()创建

2:start()  就绪

3:run() 运行

4:阻塞

5:死亡

多线程类似于同时执行多个不同程序,多线程运行有如下优点:

  • 使用线程可以把占据长时间的程序中的任务放到后台去处理。
  • 用户界面可以更加吸引人,这样比如用户点击了一个按钮去触发某些事件的处理,可以弹出一个进度条来显示处理的进度
  • 程序的运行速度可能加快
  • 在一些等待的任务实现上如用户输入、文件读写和网络收发数据等,线程就比较有用了。在这种情况下我们可以释放一些珍贵的资源如内存占用等等

实例:

 
 
import _thread  #导入_thread模块
import time  #导入time模块

为线程定义一个函数
def print_time( threadName, delay):
   count = 0
   while count < 5:
      time.sleep(delay)#设置时间的休息时长
      count += 1
      print ("%s: %s" % ( threadName, time.ctime(time.time()) ))

# 创建两个线程
try:
   _thread.start_new_thread( print_time, ("Thread-1", 2, ) )
   _thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
   print ("Error: 无法启动线程")
input("")#让进程不要停止,才能让线程有时间运行
 
 

import threading  #导入threading模块
import time  导入time模块
class Mythread(threading.Thread):
    def __init__(self,name):
        threading.Thread.__init__(self)
        self.name=name
    print("mythread......")
    def run(self):
        for i in range(10):
            print(self.name,i)
            time.sleep(1)
t=Mythread("th1")
t1=Mythread("th2")
t.start()#启动第一个线程
t.join()#join()让进来的线程先运行,其他的线程停止
t1.start()


猜你喜欢

转载自blog.csdn.net/qq_41655148/article/details/79451378