2018.1.15python-24-多线程

#!/usr/bin/python
import time
#利用time函数,
import _thread as thread
# print ("time.time(): %s " %time.time())
# print (time.localtime( time.time() ))
# print (time.asctime( time.localtime(time.time()) ))
def loop1():
    print("start loop 1 at :",time.ctime())
    time.sleep(4)
    print("end loop 1 at: ",time.ctime())
def loop2():
    print("start loop 2 at :",time.ctime())
    time.sleep(2)
    print("end loop 2 at: ",time.ctime())
def main():
    print("strting at:", time.ctime())
    thread.start_new_thread(loop1,())
    thread.start_new_thread(loop2,())

    print("all done at :", time.ctime())



if __name__ == '__main__':
    main()
    while True:
        time.sleep(1)
  • 案例1:顺序执行,耗时比较长

  • 案例2:改用多线程,缩短总时间,使用_thread

  • 案例3:多线程传参数

    import time

    import _thread as thread

 案例3:多线程传参数
def loop1(in1):
    print("start loop 1 at :",time.ctime())
    print("in1",in1)
    time.sleep(4)
    print("end loop 1 at: ",time.ctime())
def loop2(in1,in2):
    print("in1:",in1,"in2:",in2)
    print("start loop 2 at :",time.ctime())
    time.sleep(2)
    print("end loop 2 at: ",time.ctime())
def main():
    print("strting at:", time.ctime())
    thread.start_new_thread(loop1,("hello world",))
    thread.start_new_thread(loop2,("hello world","hello world2"))

    print("all done at :", time.ctime())

if __name__ == '__main__':
    main()
    while True:
        time.sleep(1)

相关文章:

  • 2021-12-19
  • 2021-05-24
  • 2021-09-11
  • 2022-02-09
  • 2021-12-25
  • 2022-12-23
  • 2021-10-29
  • 2021-05-09
猜你喜欢
  • 2021-06-12
  • 2021-06-24
  • 2021-12-25
  • 2022-01-18
  • 2021-09-09
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案