python 多线程

方式一:

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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值