线程

###一、多线程
每个程序在运行的时候(进程)系统都会为这个进程创建一个线程,这个线程我们叫主线程。
程序员自己创建的线程叫子线程

多个任务在一个线程中是按顺序一个一个执行的(线程的串行)

多个线程的任务同时执行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import time
import datetime
from random import randint
import threading


def download(file):
print(file,threading.current_thread())
print(datetime.datetime.now(),'开始下载:%s' % file)

# sleep(时间): 会将当前线程阻塞指定的时间(停指定的时间然后再往后执行)
# 时间单位:秒
time1 = randint(5, 10)
time.sleep(time1)

print(datetime.datetime.now(),'下载%s结束'%file,'总共耗时:%d' % time1)


"""
python通过threading标准库来支持多线程
"""

if __name__ == '__main__':

# download('肖生克的救赎')
# current_thread()获取当前线程
print(threading.current_thread())

# 1.创建一个线程对象
"""
Thread(target=, args=)
target: 需要传一个需要在子线程中执行的函数(类型是function的变量)
agrs: 在子线程中调用target对应的函数的时候,该传什么参数。类型是元祖
"""
t1 = threading.Thread(target=download, args=('阿甘正传',))
t2 = threading.Thread(target=download, args=('肖生克的救赎',))

# 2.让子线程去执行任务
t1.start()
t2.start()

print('===========')

###二创建线程二

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
from threading import Thread,current_thread
import time
from datetime import datetime

"""
创建线程方式1:
直接通过Thread类创建对象,将需要在子线程中执行的函数作为target参数传进去

创建线程方式2:
a.写一个自己的类去继承Thread类
b.重写当前类的run方法,run中的任务就是在子线程中执行的任务
c.创建当前类的对象, 就是线程对象。然后调用start去执行线程中任务
"""


# 1.创建线程类
class DownLoadThread(Thread):

"""下载线程类"""
def __init__(self, file):
super().__init__()
self.file = file

def run(self):
# 注意:如果需要给run方法中传数据,通过当前类的属性来传
print('%s开始下载:' % self.file, datetime.now())
time.sleep(5)
print('%s下载结束:' % self.file, datetime.now())


# 2.创建线程对象
t1 = DownLoadThread('阿甘正传')
t2 = DownLoadThread('沉默的羔羊')
# 3.通过start去执行run中的任务
"""
注意: 如果直接调用run方法,run方法中的任务不会在当前的子线程中执行
"""
# t1.run()
t1.start()
t2.start()

###用多线程写服务器和客户端

####1.服务器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import socket
from threading import Thread

class ConversationThread(Thread):
def __init__(self, conversation: socket.socket, addr):
super().__init__()
self.conversation = conversation
self.addr = addr

def run(self):
# 保持通话
while True:
# 接收消息
message_re = self.conversation.recv(1024).decode('utf-8')
print(self.addr[0], ':', message_re)

# 发送消息
message = 'hi %s,你好!' % self.addr[0]
self.conversation.send(message.encode('utf-8'))



def creat_server():
server = socket.socket()
server.bind(('10.7.156.97', 8081))
server.listen(512)

# 让服务器一直运行
while True:
# 会阻塞线程
conversation, addr = server.accept()

# 创建处理这个请求对应的子线程
t = ConversationThread(conversation, addr)
t.start()



if __name__ == '__main__':
creat_server()

####2.客户端

1
2
3
4
5
6
7
8
9
10
11
12

import socket

client = socket.socket()
client.connect(('10.7.156.97', 8081))

while True:
message = input('>>>')
client.send(message.encode('utf-8'))

message_re = client.recv(1024).decode('utf-8')
print(message_re)