进程与线程的区别:进程不共享空间,线程共享地址空间 线程共享空间优缺点:优点:多线程给用户的体验好些,处理速度快些缺点:共享地址空间相互影响
1 import threading 2 import time 3 4 class Mythreading(threading.Thread): 5 def __init__(self,threadID,name,counter): 6 threading.Thread.__init__(self) #固定格式 7 self.threadID = threadID 8 self.name = name 9 self.counter = counter 10 print("初始化完成") 11 def run(self): #由cpu来处理决定线程间的执行顺序 12 print("开始"+self.name) 13 print_time(self.name,self.counter,5) 14 print("结束"+self.name) 15 16 def print_time(threasName,counter,delay): 17 while counter: 18 time.sleep(delay) 19 print("%s:%s"%(threasName,time.ctime(time.time()))) 20 counter -= 1 21 22 #创建线程 23 thread1 = Mythreading(1,"thread1",1) 24 thread2 = Mythreading(2,"thread2",2) 25 26 #开启线程 27 thread1.start() 28 thread2.start()
1 import threading 2 import time 3 4 class Mythreading(threading.Thread): 5 def __init__(self,threadID,name,counter): 6 threading.Thread.__init__(self) #固定格式 7 self.threadID = threadID 8 self.name = name 9 self.counter = counter 10 print("初始化完成") 11 def run(self): #由cpu来处理决定线程间的执行顺序 12 threadLock.acquire() #获得锁,成功获得锁定后返回True,可选的参数timeout不填时将一直阻塞直到获得锁定 13 print_time(self.name,self.counter,3) 14 threadLock.release() #释放锁,开始下一个线程 15 16 def print_time(threasName,counter,delay): 17 while counter: 18 time.sleep(delay) 19 print("%s:%s"%(threasName,time.ctime(time.time()))) 20 counter -= 1 21 22 threadLock = threading.Lock() 23 threads = [] 24 25 #创建线程 26 thread1 = Mythreading(1,"thread1",1) 27 thread2 = Mythreading(2,"thread2",2) 28 29 #开启线程 30 thread1.start() 31 thread2.start() 32 33 # thread1.join() 34 # thread2.join() 35 threads.append(thread1) 36 threads.append(thread2) 37 for t in threads: 38 t.join() #后边的代码必须等待,等线程运行完成才会往后运行代码 39 40 print("我的的花儿也谢了")
生产者与消费者示例:
1 import threading 2 class Produce(threading.Thread): 3 4 def __init__(self,name): 5 threading.Thread.__init__(self) 6 self.name = name 7 def run(self): 8 global x 9 tt.acquire() 10 if x > 0 : 11 12 print("我不生产了") 13 else: 14 for i in range(5): 15 x += 1 16 print("%s在生产中,第%d个"%(self.name,x)) 17 tt.release() 18 19 class Consume(threading.Thread): 20 def __init__(self,name): 21 threading.Thread.__init__(self) 22 self.name = name 23 def run(self): 24 global x 25 tt.acquire() 26 if x == 0: 27 28 print("我不消费了") 29 else: 30 for i in range(5): 31 x -= 1 32 print("%s在消费中,第%d个"%(self.name,x+1)) 33 tt.release() 34 x = 0 35 tt = threading.Lock() 36 # tt = threading.Condition 37 38 p = Produce("produce") 39 c = Consume("consume") 40 41 p.start() 42 c.start() 43 44 p.join() 45 c.join()
时间: 2024-10-16 04:42:50