1、单线程应用
from time import ctime, sleep
from time import ctime, sleep
class ThreadClass:
def say(self):
print('Begin say:%s' % ctime())
sleep(2)
def write(self):
print('Brgin write:%s' % ctime())
sleep(2)
if __name__ == '__main__':
t = ThreadClass()
t.say()
t.write()
print('All end:%s' %ctime())
Begin say:Wed Jun 12 17:14:11 2019
Brgin write:Wed Jun 12 17:14:13 2019
All end:Wed Jun 12 17:14:15 2019
2、多线程的应用
from time import ctime, sleep
import threading
class ThreadClass:
def say(self, content, loop):
for i in range(loop):
print('Say:%s,Time:%s' % (content, ctime()))
sleep(2)
def write(self, content, loop):
for i in range(loop):
print('Write:%s,Time:%s' % (content, ctime()))
sleep(2)
if __name__ == '__main__':
threadings = []
tc = ThreadClass()
t1 = threading.Thread(target=tc.say, args=('say content', 2))
t2 = threading.Thread(target=tc.write, args=('write content', 2))
threadings.append(t1)
threadings.append(t2)
for t in threadings:
t.start()
for t in threadings:
t.join()
print('All the end:%s' % ctime())
Say:say content,Time:Wed Jun 12 21:58:31 2019
Write:write content,Time:Wed Jun 12 21:58:31 2019
Write:write content,Time:Wed Jun 12 21:58:33 2019
Say:say content,Time:Wed Jun 12 21:58:33 2019
All the end:Wed Jun 12 21:58:35 2019
3、扩展:多进程的应用
from time import ctime, sleep
import multiprocessing
class ThreadClass:
def say(self, content, loop):
for i in range(loop):
print('Say:%s,Time:%s' % (content, ctime()))
sleep(2)
def write(self, content, loop):
for i in range(loop):
print('Write:%s,Time:%s' % (content, ctime()))
sleep(2)
if __name__ == '__main__':
multiprocessings = []
tc = ThreadClass()
t1 = multiprocessing.Process(target=tc.say, args=('say content', 2))
t2 = multiprocessing.Process(target=tc.write, args=('write content', 2))
multiprocessings.append(t1)
multiprocessings.append(t2)
for t in multiprocessings:
t.start()
for t in multiprocessings:
t.join()
print('All the end:%s' % ctime())
Say:say content,Time:Wed Jun 12 22:03:54 2019
Write:write content,Time:Wed Jun 12 22:03:54 2019
Say:say content,Time:Wed Jun 12 22:03:56 2019
Write:write content,Time:Wed Jun 12 22:03:56 2019
All the end:Wed Jun 12 22:03:58 2019