个人总结创建多线程步骤:
1. import threading
2. 创建线程列表 threads = []
3. 开辟线程 t1 = threading.Thread(…………) 这里注意用args传参是个元组
4. for t in threads循环线程列表,在循环体中用t.setDaemon(True)设置为守护线程后,如果不设置为守护线程程序会被无限挂起,在调用t.start()开始
5. 在for循环外用t.jion()阻塞父线程
class threading.Thread()说明:
class threading.Thread(group=None, target=None, name=None, args=(), kwargs={})
This constructor should always be called with keyword arguments. Arguments are:
group should be None; reserved for future extension when a ThreadGroup class is implemented.
target is the callable object to be invoked by the run() method. Defaults to None, meaning nothing is called.
name is the thread name. By default, a unique name is constructed of the form “Thread-N” where N is a small decimal number.
args is the argument tuple for the target invocation. Defaults to (). 注意这里是个元组
kwargs is a dictionary of keyword arguments for the target invocation. Defaults to {}.
If the subclass overrides the constructor, it must make sure to invoke the base class constructor (Thread.__init__()) before doing
anything else to the thread.
程序1:
1 #coding=utf-8 2 import threading #导入threading包 3 from time import sleep,ctime 4 import time 5 6 def task1(): 7 print ("Task 1 executed at %s\n" %ctime()) 8 sleep(3) 9 10 def task2():11 print ("Task 2 executed %s\n" %ctime())12 sleep(5)13 14 print("多线程:")15 starttime=time.time(); #记录开始时间16 threads = [] #创建一个线程列表,用于存放需要执行的子线程17 t1 = threading.Thread(target=task1) #创建第一个子线程,子线程的任务是调用task1函数,注意函数名后不能有()18 threads.append(t1)#将这个子线程添加到线程列表中19 t2 = threading.Thread(target=task2)#创建第二个子线程20 threads.append(t2)#将这个子线程添加到线程列表中21 22 for t in threads: #遍历线程列表23 t.setDaemon(True) #将线程声明为守护线程,必须在start() 方法调用之前设置,如果不设置为守护线程程序会被无限挂起24 t.start() #启动子线程25 t.join()#jion()的作用是,在子线程完成运行之前,这个子线程的父线程将一直被阻塞26 endtime=time.time();#记录程序结束时间27 totaltime=endtime-starttime;#计算程序执行耗时28 print ("耗时:{0:.5f}秒" .format(totaltime)); #格式输出耗时29 print('---------------------------')30 31 #以下为普通的单线程执行过程,不需解释32 print("单线程:")33 starttime=time.time();34 task1();35 task2();36 endtime=time.time();37 totaltime=endtime-starttime;38 print ("耗时:{0:.5f}秒" .format(totaltime));
运行结果:
程序2:
1 import threading 2 from time import sleep,ctime,time 3 4 def music(m): 5 print("I am listening %s at %s"%(m,ctime())) 6 sleep(2) 7 8 def movie(v): 9 print("I am seeing %s at %s" %(v,ctime()))10 sleep(4)11 12 threads = []13 t1 = threading.Thread(target=music,args=("心动",))14 threads.append(t1)15 t2 = threading.Thread(target=movie,args=("煎饼侠",))16 threads.append(t2)17 18 if __name__ == '__main__':19 for t in threads:20 t.setDaemon(True)21 t.start()22 t.join()23 print("all the threads over at %s" %ctime())
运行结果:
程序3:
socket server和client双向传文件,这里文件路径是写死的,根据自己需求修改:
server:
1 #coding=utf-8 2 import socket 3 import threading 4 from time import ctime 5 6 BUFFERSIZE = 1024 7 HOST = '127.0.0.1' 8 PORT = 9999 9 10 #建立socket连接11 s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)12 s.bind((HOST,PORT))13 s.listen(1)14 conn,addr = s.accept()15 print("Conneted by: %s"%(addr,))16 17 #收文件18 def recvfile(filename):19 f = open(filename,'wb')20 while True:21 data = conn.recv(BUFFERSIZE)22 if str(data)[-4:] == 'EOF\'':23 f.write(data[:-3])24 break25 f.write(data)26 f.close()27 print("File received from: %s at %s"%(addr,ctime()))28 29 def sendfile(filename):30 f = open(filename,'rb')31 f_data = f.read()32 f.close()33 conn.sendall(f_data)34 conn.send(('EOF').encode())35 print("Server send finished at %s" %ctime())36 37 recvname = "d:\\2.mp4"38 sendname = "d:\\a.mp4"39 40 threads = []41 t1 = threading.Thread(target=recvfile,args=(recvname,))42 threads.append(t1)43 t2 = threading.Thread(target=sendfile,args=(sendname,))44 threads.append(t2)45 46 if __name__ == "__main__":47 48 for t in threads:49 t.setDaemon(True)50 t.start()51 t.join()52 conn.close()
client:
1 import socket 2 import threading 3 from time import ctime 4 5 BUFFERSIZE = 1024 6 HOST = '127.0.0.1' 7 PORT = 9999 8 9 s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)10 s.connect((HOST,PORT))11 12 def sendfile(filename):13 f = open(filename,'rb')14 f_data = f.read()15 f.close()16 s.sendall(f_data)17 s.send(('EOF').encode())18 print("Client send finished at %s" %ctime())19 20 def recvfile(filename):21 f = open(filename,'wb')22 while True:23 data = s.recv(BUFFERSIZE)24 if str(data)[-4:] == 'EOF\'':25 f.write(data[:-3])26 break27 f.write(data)28 f.close()29 print("File received from: %s at %s"%(HOST,ctime()))30 31 sendname = "e:\\1.mp4"32 recvname = "e:\\b.mp4"33 34 threads = []35 t1 = threading.Thread(target=sendfile,args=(sendname,))36 threads.append(t1)37 t2 = threading.Thread(target=recvfile,args=(recvname,))38 threads.append(t2)39 40 41 if __name__ == "__main__":42 for t in threads:43 t.setDaemon(True)44 t.start()45 t.join()46 s.close()