多线程
Thread是线程类,有两种使用方法,直接传入要运行的方法或
1.从Thread继承并覆盖run():
import threading import time class MyThread(threading.Thread): def __init__(self, n): super(MyThread, self).__init__() self.n = n def run(self): print("runnint task", self.n) t1 = MyThread("t1") t2 = MyThread("t2") t1.start() # runnint task t1 #t1.join() t2.start() # runnint task t2 #t2.join()
1.当用继承的方式去创建线程时,一定要重写父类的Run()方法
2.当线程的run()方法结束的时候,线程也结束
3.我们认为是无法完全控制线程的,但是我们可以通过一些方式来影响线程的调用
4.线程的几种状态 新建----就绪----运行-----死亡 等待(阻塞)主要出现就绪与运行之间
5.在UNIX平台上,当某个进程终结之后,该进程需要被其父进程调用wait,否则进程成为僵尸进程(Zombie)。所以,有必要对每个Process对象调用join()方法 (实际上等同于wait)。对于多线程来说,由于只有一个进程,所以不存在此必要性。
2.直接传入要运行的方法
""" 例1: # 假定这是你的银行存款: balance = 0 lock = threading.Lock() def change_it(n): # 先存后取,结果应该为0: global balance balance = balance + n balance = balance - n def run_thread(n): #lock = threading.Lock() global lock for i in range(100000): lock.acquire() try: # 放心地改吧: change_it(n) finally: # 改完了一定要释放锁: lock.release(): t1 = threading.Thread(target=run_thread, args=(5,)) t2 = threading.Thread(target=run_thread, args=(8,)) t1.start() t2.start() #t1.join() #t2.join() print balance 例2: #新线程执行的代码: def loop(fn,a,b): print fn,a,b print 'thread %s is running...',threading.current_thread().name n = 0 while n < 5: n = n + 1 print "thread %s>>>%s",threading.current_thread().name,n time.sleep(1) print "thrad %s end",threading.current_thread().name print "thread %s is running...",threading.current_thread().name filename = "tgets.csv" t = threading.Thread(target=loop,name="LoopThread",args=(filename,5,5)) t.start() t.join() print "thread %s ended.",threading.current_thread().name 例3: hehe=6 def f(): global hehe print(hehe) hehe=3 f() print(hehe) """