import threading
import time
def run(name):
print(name,"线程执行了!")
time.sleep(5)
t1=threading.Thread(target=run,args=("t1",))
t2=threading.Thread(target=run,args=("t2",))
t1.start()
t2.start()
t1.join()
t2.join()
print("执行完毕")
import threading
import time
class myThread(threading.Thread):
def __init__(self,name):
threading.Thread.__init__(self)
self.name = name
def run(self):
print("开始线程",self.name)
print("线程执行中---1")
time.sleep(1)
print("线程执行中---2")
time.sleep(1)
print("线程执行中---3")
time.sleep(1)
print("线程执行中---4")
time.sleep(1)
print("线程执行中---5")
time.sleep(1)
print("结束线程",self.name)
t1=myThread("t1")
t2=myThread("t2")
t3=myThread("t3")
t1.start()
t2.start()
t3.start()
t1.join()
t2.join()
t3.join()
print("执行完毕")
import queue
q=queue.Queue(maxsize=10)
for i in range(1,11):
q.put(i)
while not q.empty():
print(q.get())
import threading
import queue
import requests
import time
from lxml import etree
class Thread1(threading.Thread):
def __init__(self, threadName,pageQueue,dataQueue):
threading.Thread.__init__(self)
self.threadName = threadName
self.pageQueue = pageQueue
self.dataQueue = dataQueue
self.headers = {"User-Agent" : "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0;"}
def run(self):
print("启动线程"+self.threadName)
while not flag1:
try:
page=self.pageQueue.get()
url="https://www.qiushibaike.com/8hr/page/"+str(page)+"/"
content=requests.get(url,headers=self.headers).text
time.sleep(0.5)
self.dataQueue.put(content)
except Exception as e:
pass
print("结束线程"+self.threadName)
class Thread2(threading.Thread):
def __init__(self, threadName,dataQueue,filename):
threading.Thread.__init__(self)
self.threadName = threadName
self.dataQueue = dataQueue
self.filename = filename
def run(self):
print("启动线程"+self.threadName)
while not flag2:
try:
data1=self.dataQueue.get()
html=etree.HTML(data1)
node_list=html.xpath('//div/a[@class="recmd-content"]')
for node in node_list:
data=node.text
self.filename.write(data+"\n")
except Exception as e:
pass
print("结束线程"+self.threadName)
flag1=False
flag2=False
def main():
pageQueue=queue.Queue(10)
for i in range(1,11):
pageQueue.put(i)
dataQueue=queue.Queue()
filename=open(r"C:\file\dianzi.txt","a")
t1=Thread1("采集线程",pageQueue,dataQueue)
t1.start()
t2=Thread2("解析线程",dataQueue,filename)
t2.start()
while not pageQueue.empty():
pass
global flag1
flag1=True
while not dataQueue.empty():
pass
global flag2
flag2=True
t1.join()
t2.join()
filename.close()
print("结束!")
if __name__ == '__main__':
main()