threading伪多线程
importthreading, time
defrun(n):
print("task", n)
time.sleep(2)
t1 = threading.Thread(target=run,args=("t1",))
t2 = threading.Thread(target=run,args=("t2",))
t1.start()
t2.start()
run("t1")
run("t2")
importthreading, time
classMyThread(threading.Thread):
def__init__(self, n):
super(MyThread,self).__init__()
self.n = n
defrun(self):
print("running task",self.n)
time.sleep(2)
t1 = MyThread("t1")
t2 = MyThread("t2")
t1.run()
t2.run()
t1.start()
t2.start()
importthreading, time
defrun(n):
print("task", n)
time.sleep(2)
print("task done", n, threading.current_thread()) #打印子线程
start_time = time.time()
t_objs = []
foriinrange(50):
t = threading.Thread(target=run,args=("t %s"% i,))
t.start()
t_objs.append(t) #把每个线程实例都加进来 不阻塞后面线程的启动
fortint_objs: #取列表里的每个线程
t.join() #等待并行的每个线程全都执行完毕 在往下走
print("----all threads has finished...", threading.current_thread(), threading.active_count()) #打印主线程,程序默认有一个主线程
print("cost:", time.time() - start_time) # threading.active_count()活跃线程个数 import time,threading
importtime,threading
classMyThread(threading.Thread):
def__init__(self, n, sleep_time):
super(MyThread,self).__init__()
self.n = n
self.sleep_time = sleep_time
defrun(self):
print("running task",self.n)
time.sleep(self.sleep_time)
print("task done",self.n)
t1 = MyThread("t1",2) #等待2秒
t2 = MyThread("t2",4) #等待4秒
t1.start()
t2.start()
t1.join() # wait()等待t1线程执行完再往下走 程序进程变成串行了 主程序卡主了
t2.join() # t1执行完之后等t2等待t2执行完之后再往下走
print("main threading....")
#程序末尾有一个默认的join守护线程
importthreading, time
defrun(n):
print("task", n)
time.sleep(2)
print("task done", n, threading.current_thread()) #打印子线程 如果不设置为守护线程,那么程序会执行到这里
start_time = time.time()
t_objs = []
foriinrange(50):
t = threading.Thread(target=run,args=("t %s"% i,))
t.setDaemon(True) #设置为守护线程 设置为守护线程之后,主线程执行完之后程序就退出了,不管守护线程有没有执行完都会退出
t.start()
t_objs.append(t) #把每个线程实例都加进来 不阻塞后面线程的启动
# for t in t_objs: #取列表里的每个线程
# t.join() #等待并行的每个线程全都执行完毕 在往下走
print("----all threads has finished...")
print("cost:", time.time() - start_time)
网站名称:threading伪多线程
当前URL:http://azwzsj.com/article/jhojid.html