方式一:
import _thread
#---------------_thread实现简单多线程----------------
def run(name):
print(name)
try:
_thread.start_new_thread(run,("AAA",))
_thread.start_new_thread(run,("BBB",))
except:
print("无法启动线程")
方式二:
import threading
#----------------lock实现同步------------
class ThreadTest(threading.Thread):
def __init__(self,name):
threading.Thread.__init__(self)
self.name=name
def run(self):
global x
lock.acquire()
if self.name is "AAA":
x+=1
else:
x-=1
print(self.name,x)
lock.release()
x=50
lock=threading.Lock()
thread1=ThreadTest("AAA")
thread2=ThreadTest("BBB")
thread1.start()
thread2.start()
方式三:
import threading
import queue
#--------------------------队列实现------------------------------
class myThread1(threading.Thread):
def __init__(self,name):
threading.Thread.__init__(self)
self.name=name
def run(self):
global que
item=que.get()
if(self.name is "AAA"):
item+=1
else:
item -= 1
que.put(item)
print(self.name, item)
que=queue.Queue()
x=50
mythread=[]
que.put(x)
for i in range(1,3):
if i==1:
mythread.append(myThread1("BBB"))
else:
mythread.append(myThread1("AAA"))
for item in mythread:
item.start()
方式四:
#-----------------------------线程池加队列实现------------------------
class myThread:
def __init__(self,name):
self.name=name
def run(self):
global que
item=que.get()
if item>=50:
item-=1
else:
item+=1
que.put(item)
print(self.name,item)
x=50
que=queue.Queue()
que.put(x)
thread_pool=ThreadPoolExecutor(max_workers=5)
for i in range(10):
result=thread_pool.submit(myThread(f"Thread:{i}").run())
print(result)