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 Thread(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(thread_name, delay):
count = 0
while count < 3:
time.sleep(delay)
print(thread_name, time.ctime())
count += 1
threads = []
# 创建新线程
thread1 = Thread("Thread-1", 1)
thread2 = Thread("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(0.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() # 将线程加入到主线程中