Python线程的用法 函数式线程_thread和threading 样例

函数式线程写起来比较简单,但是功能没有threading那么高级,先来个函数式编程样例:

#!/usr/bin/python
#coding: utf-8


#————————————————————————函数式线程————————————————————————————————————————
#QQ496631085  小和   XiaoHe
import _thread
import time

def     print_time(threadName,delay):
    count = 0
    while count<4:
        time.sleep(delay)
        count += 1
        print(threadName,time.ctime())

print(time.ctime())#打印现在时间以方便对比
_thread.start_new_thread(print_time,("thread-1",2))
_thread.start_new_thread(print_time,("thread-2",4))
time.sleep(200)#不加这个有的编译器,直接到最后就停止整个程序运行了,看不出效果
print("end")

#————————————————————————函数式线程————————————————————————————————————————

 

 

然后就是threading线程样例:

#!/usr/bin/python
#coding: utf-8



#===========================threading========================================

#QQ496631085  XiaoHe
import threading
import time

class myThread(threading.Thread):
    """docstring for myThread"""
    def __init__(self, name,delay):
        threading.Thread.__init__(self)
        print(name+"线程开始时间" +time.ctime())

        self.name =name
        self.delay = delay

    def run(self):
        print("Starting " + self.name + time.ctime())
        print_time(self.name, self.delay)
        print("Exiting " + self.name + time.ctime())

def print_time(threadName, delay):
    counter = 0
    while counter < 3:
        time.sleep(delay)
        print("延时" + threadName  ,time.ctime())
        counter+=1



threads =[]
#创建新线程
thread1= myThread("Thread-111",2)
thread2= myThread("Thread-222",4)

#开始新线程
thread1.start()
thread2.start()

#添加线程到线程列表   然后一直等待线程终止
threads.append(thread1)
threads.append(thread2)

#等待线程结束
for t in threads:
    t.join()
print("线程结束")
#===========================threading========================================

 如果觉得这个还慢有不足的地方,可以试试queue的多线程爬虫

转载于:https://www.cnblogs.com/xiaohe520/p/10767361.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值