1. 使用`threading.Thread`类:
import threading
def worker():
print("这是一个线程!")
t = threading.Thread(target=worker)
t.start()
t.join()
2. 使用`threading.Thread`的子类,并重写`run`方法:
import threading
class MyThread(threading.Thread):
def run(self):
print("这是一个自定义线程!")
t = MyThread()
t.start()
t.join()
3. 使用`threading.Thread`的构造函数,传递函数名、参数和关键字参数:
import threading
def worker(name):
print(f"{name}开始")
time.sleep(0.5)
print(f"{name}结束")
t = threading.Thread(target=worker, args=("线程1",))
t.start()
t.join()
4. 使用`_thread`模块的`start_new_thread`函数:
import _thread
import time
def hello(id=0, interval=2):
for i in range(10):
if i % interval == 0:
print(f"Thread id: {id}, time is {i}")
_thread.start_new_thread(hello, (1,))
_thread.start_new_thread(hello, (2,))
_thread.start_new_thread(hello, (), {"id": 1})
_thread.start_new_thread(hello, (), {"id": 2})
5. 使用`threading.Thread`的`target`参数直接传递函数:
import threading
def writing():
print("我正在写字")
time.sleep(1)
def drawing():
print("我正在绘画")
time.sleep(1)
t1 = threading.Thread(target=writing)
t2 = threading.Thread(target=drawing)
t1.start()
t2.start()
t1.join()
t2.join()
6. 使用`threading.Thread`的`name`参数给线程命名:
import threading
def worker(name):
print(f"线程 {name} 开始")
time.sleep(0.5)
print(f"线程 {name} 结束")
t = threading.Thread(target=worker, args=("线程1",), name="线程1")
t.start()
t.join()
注意:在使用多线程时,需要注意线程同步问题,避免竞态条件和死锁等问题。可以使用`Lock`、`Condition`、`Semaphore`等工具来帮助管理线程