Python多线程

介绍

什么是线程?

  线程也叫轻量级进程,是操作系统能够进行运算调度的最小单位,它被包涵在进程之中,是进程中的实际运作单位。
  线程自己不拥有系统资源,只拥有一点儿在运行中必不可少的资源,但它可与同属一个进程的其他线程共享进程所
  拥有的全部资源。一个线程可以创建和撤销另一个线程,同一个进程中的多个线程之间可以并发执行

多线程运行有如下优点:

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

函数式

调用thread模块中的start_new_thread()函数来产生新线程

thread.start_new_thread ( function, args[, kwargs] )

例如:

import thread
import 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: unable to start thread"
 
while 1:
   pass

线程的结束一般依靠线程函数的自然结束;也可以在线程函数中调用thread.exit(),他抛出SystemExit exception,达到退出线程的目的。

线程模块

使用Threading模块创建线程,直接从threading.Thread继承,然后重写__init__方法和run方法:

class MyThread(threading.Thread):
     def __init__(self,n):
         super(MyThread,self).__init__()   #重构run函数必须写
         self.n = n

     def run(self):
         print('task',self.n)
         time.sleep(1)
         print('2s')
         time.sleep(1)
         print('1s')
         time.sleep(1)
         print('0s')
         time.sleep(1)

 if __name__ == '__main__':
     t1 = MyThread('t1')
     t2 = MyThread('t2')
     t1.start()
     t2.start()

本次作业

"""
在一个线程中,每秒循环输出当前的年月日时分秒;于此同时,
在另一个线程中,实现张三的姓名每 2 秒打印输出 4 次结束。

"""
import threading
import time

class myThread(threading.Thread):  # 继承父类threading.Thread
    def __init__(self, name, ):
        super(myThread, self).__init__()
        self.name = name

    def run(self):  # 把要执行的代码写到run函数里面 线程在创建后会直接运行run函数
        print_name(self.name, 4)  

def print_time(count):  # 定义时间打印函数
    while count:
        time1 = time.ctime(time.time())
        print("%s" % time1)
        time.sleep(1)
        count -= 1

def print_name(Name, counter):  # 定义姓名打印函数
    while counter:
        print("%s" % Name)
        time.sleep(2)
        counter -= 1

if __name__ == '__main__':  # 定义主接口
    thread1 = threading.Thread(target=print_time, args=(8,))  # 创建时间线程
    thread2 = myThread("张三")  # 创建姓名线程

    thread1.start()
    thread2.start()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值