Python 多线程(1)

import _thread
import time

# 为线程定义一个函数
def print_time(threadName, delay):
    count = 0
    while count < 3:
        time.sleep(delay)
        count += 1
        print(threadName, time.ctime())

# 创建两个线程
try:
    _thread.start_new_thread(print_time, ("Thread-1", 1)) # 休眠1秒
    _thread.start_new_thread(print_time, ("Thread-2", 2)) # 休眠2秒
except:
    print("Error: unable to start thread")
while 1:
    pass

和_thread几乎一样,但是使用threading能够有效控制线程,将在网络爬虫中发挥更好的效果

import threading
import time


class Thread(threading.Thread):
    def __init__(self, name, delay):
        threading.Thread.__init__(self)
        self.name = name
        self.delay = delay

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


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


threads = []

# 创建新线程
thread1 = Thread("Thread-1", 1)
thread2 = Thread("Thread-2", 2)

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

# 添加线程到线程列表
threads.append(thread1)
threads.append(thread2)

# 等待所有线程完成
for t in threads:
    t.join()

print("Exiting Main Thread")

3.Python多线程同步输出1-100的数

import threading, time


def worker():
    global count
    while True:
        lock.acquire()  # 加锁
        count += 1
        print(threading.current_thread(), count)
        lock.release()  # 操作完成后释放锁
        if count >= 99:
            break
        time.sleep(0.1)


if __name__ == '__main__':
    lock = threading.Lock()
    count = 0
    threads = []
    for i in range(2):  # 控制线程的数量
        t = threading.Thread(target=worker, args=())
        threads.append(t)
    for i in threads:
        i.start()
    for i in threads:
        i.join()  # 将线程加入到主线程中


参考:
1.python多线程详解(超详细)

2.Python多线程同步输出1-100的数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值