Condivisione della tecnologia

Domanda dell'intervista a Python: come eseguire la programmazione multi-thread in Python?

2024-07-08

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Per la programmazione multi-thread in Python è comune usare threading modulo. Di seguito è riportato un semplice esempio che mostra come creare e avviare più thread.

Codice d'esempio

import threading
import time

# 定义一个简单的函数,它将在线程中运行
def print_numbers():
    for i in range(10):
        print(f"Number: {i}")
        time.sleep(1)

def print_letters():
    for letter in "abcdefghij":
        print(f"Letter: {letter}")
        time.sleep(1)

# 创建线程对象
thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_letters)

# 启动线程
thread1.start()
thread2.start()

# 等待线程完成
thread1.join()
thread2.join()

print("All threads have finished execution")