线程

一、线程基本

  • start 线程准备就绪,等待CPU调度
  • setName 为线程设置名称
  • getName 获取线程名称
  • setDaemon 守护线程
  • join 逐个执行每个线程,执行完毕后继续往下执行,该方法使得多线程变得无意义
  • run 线程被cpu调度后自动执行线程对象的run方法
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 线程锁
  • Semaphore 信号量 同时允许一定数量的线程更改数据
  • event 事件 用于主线程控制其他线程的执行 set、wait、clear
  • condition 使得线程等待,只有满足某条件时,才释放n个线程
  • Timer 定时器,指定n秒后执行某操作

生产者消费者模型

你可能感兴趣的:(线程)