神奇的python的多线程

通过函数

import random
import threading
import time


def pr(num):
    for i in range(10):
        print(f"{num}:  i=:{i}")
        time.sleep(random.uniform(0, 1))


t1 = threading.Thread(target=pr, kwargs={"num": "t1"})
t2 = threading.Thread(target=pr, kwargs={"num": "t2"})
t1.start()
t2.start()
t1.join()
t2.join()
print("end")

通过类


class MyTask(threading.Thread):
    def __init__(self, name, count):
        super().__init__()
        self.name = name
        self.count = count
        self.daemon = False  # 默认为False设置成守护线程(True),则主线程结束后,此线程就会结束

    def run(self) -> None:
        for i in range(self.count):
            print(f"name={self.name},i={i}\n", end="")


t1 = MyTask("mytask1", 10)
t2 = MyTask("mytask2", 10)
t1.start()
t2.start()

线程池的使用



# 线程池

import time
from concurrent.futures import ThreadPoolExecutor


def pr(num):
    for i in range(10):
        print(f"{num}:  i=:{i}")
        time.sleep(random.uniform(0, 1))
    return f"{num} end"

with ThreadPoolExecutor() as executor:
    res = executor.map(pr, ["A", "B"])  # map同时提交多个相同任务
    for x in res:
        print(x)

with ThreadPoolExecutor() as executor:
    c = executor.submit(pr, "C")  # map同时提交多个相同任务
    d = executor.submit(pr, "D")  # map同时提交多个相同任务
    print(c.result())
    print(d.result())

你可能感兴趣的:(python,python,java,服务器)