Thread
1 # from threading import Thread
2 # import time
3 # import os
4 # def func(i):
5 # time.sleep(1)
6 # print('helloworld',i,os.getpid())
7 # thread_lst = []
8 # for i in range(10):
9 # t = Thread(target=func,args=(i,))
10 # t.start()
11 # thread_lst.append(t)
12 # [t.join() for t in thread_lst]
13 # print(os.getpid())
定义自己的Thread类
1 # from threading import Thread
2 # import time,os
3 # n = 0
4 # class MyThread(Thread):
5 # # n = 0
6 # # def __init__(self):
7 # # MyThread.n += 1
8 # def run(self):
9 # time.sleep(1)
10 # print('helloworld',n,os.getpid())
11 #
12 # l = []
13 #
14 # def func(i,l):
15 # l.append(i)
16 #
17 # for i in range(20):
18 # t = MyThread()
19 # t.start()
等待开启的线程执行完
1 # from threading import Thread
2 # import time,os,random
3 #
4 # def func(i):
5 # time.sleep(random.random())
6 # print('hello %s'%i,os.getpid())
7 #
8 # tl = []
9 # for i in range(10):
10 # t = Thread(target=func,args=(i,))
11 # t.start()
12 # tl.append(t)
13 #
14 # [t.join() for t in tl]
有段thread的一些属性
1 # from threading import Thread
2 # import time,os,random
3 #
4 # class MyThread(Thread):
5 # count = 0
6 # def __init__(self,arg1,arg2):
7 # super().__init__()
8 # self.arg1 = arg1
9 # self.arg2 = arg2
10 # def run(self):
11 # MyThread.count += 1
12 # time.sleep(random.random())
13 # print('%s,%s,%s,%s'%(self.arg1,self.arg2,self.name,os.getpid()))
14 # for i in range(10):
15 # t = MyThread(i,i*'*')
16 # t.start()
17 # print(t.count) # 计算开启的线程数量
1 from threading import Thread
2 import threading
3 import time,os,random
4 def func(i):
5 # print(len(threading.enumerate()))
6 time.sleep(random.random())
7 print(i,threading.current_thread().name,threading.current_thread().ident)
8 for i in range(10):
9 t = threading.Thread(target=func,args=(i,))
10 t.start()
11 # print('main:',len(threading.enumerate())) # # 返回正在运行着的线程列表
12 time.sleep(random.random())
13 # print('main:',len(threading.enumerate()))
14 print(threading.active_count())