0%

python线程

python线程

单线程

single_thread.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import time
import threading

def draw_circle(cost):
print("start draw a circle ", time.ctime())
time.sleep(cost)
print("draw a circle ", time.ctime())

def draw_square(cost):
print("start draw a square ", time.ctime())
time.sleep(cost)
print("draw a square ", time.ctime())

def single_thread():
draw_circle(1)
draw_square(2)

if __name__ == '__main__':
print("start single_thread ", time.ctime())
single_thread()
print("end single_thread ", time.ctime())

多线程

multi_thread.py

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
import time
import threading

def draw_circle(cost):
print("start draw a circle ", time.ctime())
time.sleep(cost)
print("draw a circle ", time.ctime())

def draw_square(cost):
print("start draw a square ", time.ctime())
time.sleep(cost)
print("draw a square ", time.ctime())

def multi_thread():
draw_circle_thread = threading.Thread(target=draw_circle, args=(1,))
draw_square_thread = threading.Thread(target=draw_square, args=(2,))
draw_circle_thread.start()
draw_square_thread.start()
draw_circle_thread.join()
draw_square_thread.join()

if __name__ == '__main__':
print("start ", time.ctime())
multi_thread()
print("end ", time.ctime())