Python 多线程(1)

it2025-06-02  7

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 myThread(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(threadName,delay): count=0 while count<3: time.sleep(delay) print(threadName,time.ctime()) count+=1 threads=[] # 创建新线程 thread1=myThread("Thread-1",1) thread2=myThread("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(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的数

最新回复(0)