Python3 basic usage of multi-threading

Source: Internet
Author: User

#coding=utf-8import threading #导入threading包from time import sleepimport timedef task1():     print ("Task 1 executed." )    sleep(1)def task2():    print ("Task 2 executed." )    sleep(5)    print("多线程:")starttime=time.time(); #记录开始时间threads = [] #创建一个线程列表,用于存放需要执行的子线程t1 = threading.Thread(target=task1) #创建第一个子线程,子线程的任务是调用task1函数,注意函数名后不能有()threads.append(t1)#将这个子线程添加到线程列表中t2 = threading.Thread(target=task2)#创建第二个子线程threads.append(t2)#将这个子线程添加到线程列表中for t in threads: #遍历线程列表    t.setDaemon(True) #将线程声明为守护线程,必须在start() 方法调用之前设置,如果不设置为守护线程程序会被无限挂起    t.start() #启动子线程endtime=time.time();#记录程序结束时间totaltime=endtime-starttime;#计算程序执行耗时print ("耗时:{0:.5f}秒" .format(totaltime)); #格式输出耗时print(‘---------------------------‘)#以下为普通的单线程执行过程,不需解释print("单线程:")starttime=time.time();task1();task2();endtime=time.time();totaltime=endtime-starttime;print ("耗时:{0:.5f}秒" .format(totaltime));

Results:

Python3 basic usage of multi-threading

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.