线程

2017-03-01  本文已影响36人  交易狗二哈

一、线程基本

  • start 线程准备就绪,等待CPU调度
import threading
import time

def foo(num):
    print('{} is runing \n'.format(num))
    time.sleep(3)
    print('{} is accomplish \n'.format(num))

t1 = threading.Thread(target=foo, args=(1,))            #创建线程,注意逗号
t2 = threading.Thread(target=foo, args=(2,))

t1.start()
t2.start()
print(t1.getName())
print(t2.getName())
t1.join()            #确保线程完成
t2.join()

print('Done')
>>> 
================== RESTART: C:\Users\Why Me\Desktop\线程基本.py ==================
1 is runing 
Thread-12 is runing 



Thread-2
2 is accomplish 
1 is accomplish 


Done

二、创建多个线程

import threading
import time

def foo(num):
    print('{} is runing \n'.format(num))
    time.sleep(3)
    print('{} is accomplish \n'.format(num))
a = []
for i in range(10):
    t = threading.Thread(target=foo, args=[i,])
    t.start()
    a.append(t)
    print(t.getName())
for i in a:
    i.join()
print('Done')

================= RESTART: C:\Users\Why Me\Desktop\创建多个线程.py =================
Thread-10 is runing 


1 is runing 
Thread-2

2 is runing 
Thread-3

3 is runing 
Thread-4

Thread-54 is runing 


5 is runing 
Thread-6

6 is runing 
Thread-7

7 is runing 
Thread-8

8 is runing 
Thread-9

9 is runing 
Thread-10

0 is accomplish 
1 is accomplish 
2 is accomplish 

3 is accomplish 

4 is accomplish 
5 is accomplish 

6 is accomplish 
7 is accomplish 
8 is accomplish 

9 is accomplish 






Done

三、自己写继承线程类

import threading
import time

def foo(num):
    print('{} is runing \n'.format(num))
    time.sleep(3)
    print('{} is accomplish \n'.format(num))

class MyThread(threading.Thread):
    def __init__(self, num):
        super(MyThread,self).__init__()                  #新式继承父类__init__
        #threading.Thread.__init__(self)                 #旧式继承父类__init__
        self.num = num

    def run(self):
        print('{} is runing \n'.format(self.num))
        time.sleep(3)
        print('{} is accomplish \n'.format(self.num))

t1 = MyThread(1)
t2 = MyThread(2)
t1.start()
t2.start()

================ RESTART: C:\Users\Why Me\Desktop\自己写继承线程类.py ================
>>> 1 is runing 
2 is runing 


1 is accomplish 
2 is accomplish 

另:

  • Lock、RLock 线程锁

生产者消费者模型

上一篇下一篇

猜你喜欢

热点阅读