【python3】多线程-线程异步(推荐使用)

版权声明:== https://github.com/fyonecon == https://blog.csdn.net/weixin_41827162/article/details/84104421

-

python3有threading和_thread两种线程写法,推荐使用threading

开多线程就是为了使用多线程的异步能力来同时执行多个线程。

1. threading方法

#!/usr/bin/python3
# 线程异步

import threading
import time

exitFlag = 0


class myThread(threading.Thread):
    def __init__(self, thread_id, name, counter):
        threading.Thread.__init__(self)
        self.thread_id = thread_id
        self.name = name
        self.counter = counter
        pass

    def run(self):
        print("开始线程=" + self.name)
        run_def(self.name, self.counter, 5)
        print("退出线程=" + self.name)
        pass
    pass


def run_def(thread_name, delay, counter):
    while counter:
        if exitFlag:
            thread_name.exit()
            pass
        time.sleep(delay)
        # time.sleep(0)
        list(thread_name)
        counter -= 1
        pass
    pass


def list(thread_name):
    print("\n执行线程=" + thread_name)
    pass


threads = []  # 存储在线线程

# 创建线程
for this_t in range(1, 10):
    t = myThread(this_t, "Thread-" + str(this_t), 0.1)
    t.start()
    threads.append(t)
    pass

# 终止线程
for t in threads:
    t.join()
    pass

print("程序完成!!")

-

2. _thread方法

import _thread


all_thread_num = 0


def page_class(cla, that_num):
    print("已启动线程=" + str(that_num))
    global all_thread_num
    all_thread_num += 1
    print("线程总数=" + str(all_thread_num))
    for page in range(1, 30):
        print("内=" + str(page))
        pass
    pass


for cla in range(20190, 20291):  # 创建线程
    try:
        _thread.start_new_thread(page_class, (cla, (cla - 20000)))
        pass
    except:
        print("无法启动线程")
        pass
    pass

while 1:
    pass

-

猜你喜欢

转载自blog.csdn.net/weixin_41827162/article/details/84104421