实现两个线程相互交替 打印奇数偶数 ,为了避免忘记记录下来

import os
import re
import time
import threading
# start_time=time.time()
# with open('1.txt','r',errors='ignore') as F:
#     A=F.read()
#
#
# patternn_sku1=r'="((https|http)://(?!item).+?!!.+?\.jpg)'
#
# B=re.findall(patternn_sku1,A,re.M)
# for i in B:
#     print(i)
# dz=os.getcwd()
# print('耗时'+str(time.time()-start_time))
# #print(dz+'\\图片\\'+url[-20:])
list1=[i for i in range (1,101)]
a=0
b=0
class mythread (threading.Thread):
    def __init__(self,h,jcid,n):
        threading.Thread.__init__(self)
        self.h=h
        self.name=jcid
        self.n=n
    def run (self):
        global a
        global b
        if self.name=='线程1':
            for i in range(len(self.h)) :
                while True:
                    if b==self.n:
                        continue
                    else:
                        b=self.n
                        break

                lock.acquire()
                #print('线程1获得锁')
                print(self.name,'提取出来了奇数',self.h[a])
                a+=1
                #判断另一个线程是否到来
                while True:
                    if b==self.n:
                        continue
                    else:
                        #print('开始释放锁')
                        lock.release()
                        time.sleep(1)
                        break

        else:
            for i in range(len(self.h)) :
                #判断上一个线程是不是自己是自己就继续循环,不是自己就进去
                while True:
                    if b==self.n:
                        continue
                    else:
                        b=self.n
                        break
                lock.acquire()
                #print('线程2获得锁')
                print(self.name, '提取出来了偶数', self.h[a])
                a+=1
                #判断另一个线程是否到来,如果不到来继续等待
                while True:
                    if b==self.n:
                        continue
                    else:
                        #print('线程2开始释放锁')
                        lock.release()
                        time.sleep(1)
                        break


xc1=mythread(list1,'线程1',1)
xc2=mythread(list1,'线程2',2)
lock=threading.Lock()
xc1.start()
xc2.start()
xc1.join()
xc2.join()

原理就是 线程1 获得锁的时候拿一个循环来判断线程2 是否带来,线程2 来的时候会判断 前面的是不是线程1,是1的话就报信,线程1就会收到 然后解除循环,解锁

 

实现方法2:这是一个大神给的答案

from threading import Thread, Lock

lock = Lock()
count = 0

def even(m):
    global count
    while count <= 10:
        if count % 2 == 0:
            with m:
                print(count)
                count += 1
        else:
            continue


def odd(m):
    global count
    while count <= 9:
        if count % 2 == 1:
            with m:
                print(count)
                count += 1
        else:
            continue




t_even = Thread(target=even, args=(lock,)).start()
t_odd = Thread(target=odd, args=(lock,)).start()

 

你可能感兴趣的:(python)