Python实现的多线程

一、通过_thread的start_new_thread 方法实现
import _thread
import time
def print_time(threadName,delay):
    count=0
    while count<5:
        time.sleep(delay)
        print("%s:%s" %(threadName,time.ctime(time.time())))
#创建2线程
try:
    _thread.start_new_thread(print_time,("thread1",1))
    _thread.start_new_thread(print_time,("thread2",1))
except:
    print_time("error :无法启动线程")
while 1:
    pass

二、通过继承threading.Thread方法实
import  random
import time,threading
    
exitFlag=0
#集成threading.Thread类
class MyThread(threading.Thread):
    # 初始化变量
    def __init__(self,name,urls):
        threading.Thread.__init__(self,name=name)
        self.urls = urls
    #实现了父类的run方法
    def run(self):
        print("current %s is running...." % threading.current_thread().name)
        print("开始线程"+self.name)
        for url in self.urls:
            print("%s---%s" % (threading.current_thread().name,url))
            time.sleep(random.random())
    print("%s si running......." % (threading.current_thread().name))

t1 = MyThread(name="Thread_1",urls=['url1','url2','url3','url4','url5'])
t2 = MyThread(name="Thread_2",urls=['url6','url7','url8','url9','url10'])
t1.start()
t2.start()
t1.join()
t2.join()
第三种通过传入函数的形势
import  random
import time,threading
name1 = "1"
name2 = "2"
print(name1+name2+"2")
def thread_run(urls):
    print("current %s is running..."% threading.current_thread().name)
    t3 = threading.Thread(target=thread_run2, name="Thread-3")
    t3.start()
    for url in urls:
        print(threading.current_thread().name+"%s is running %s"+url)
        time.sleep(random.random())
    print("%s ended ." % threading.current_thread().name)
def thread_run2():
    for i in range(5):
        print(i)
t1 = threading.Thread(target=thread_run,name="Thread-1",args=(['url1',"url2","url3"],))
t2 = threading.Thread(target=thread_run,name="Thread-2",args=(['url1',"url2","url3"],))

t1.start()
t2.start()
t1.join()
t2.join()

猜你喜欢

转载自blog.csdn.net/ying62506799/article/details/80758629