多进程和多线程python

来源:https://blog.csdn.net/lzy98/article/details/88819425

代码:

# -* coding:utf8 *-

import threading

import time

 

class mop_floor(threading.Thread):

def __init__(self):

super(mop_floor,self).__init__()

 

def run(self):

print('我要拖地了')

time.sleep(1)

print('地拖完了')

 

class heat_up_watrt(threading.Thread):

def __init__(self,name):

# 这里传入参数name,就是传入子线程名字

super(heat_up_watrt,self).__init__(name=name)

# 记住这里的格式不能错

 

def run(self):

print('我要烧水了')

print(self.name)

print(threading.current_thread().name)

# 这两个都是打印出当前子线程的名字

time.sleep(6)

print('水烧开了')

if __name__=="__main__":

start_time = time.time()

t1 = mop_floor()

t2 = heat_up_watrt('***我是烧水员***')

t1.start()

t2.start()

t1.join()

t2.join()

end_time = time.time()

print('总共耗时:{}'.format(end_time-start_time))

代码:

# -* coding:utf8 *-
import threading
def run1():
  while 1:
    if l1.acquire():
      # 如果第一把锁上锁了
      print('我是老大,我先运行')
      l2.release()
      # 释放第二把锁
def run2():
  while 1:
    if l2.acquire():
      # 如果第二把锁上锁了
      print('我是老二,我第二运行')
      l3.release()
      # 释放第三把锁
def run3():
  while 1:
    if l3.acquire():
      # 如果第三把锁上锁了
      print('我是老三,我最后运行')
      l1.release()
      # 释放第一把锁

if __name__=='__main__':
    t1 = threading.Thread(target=run1)
    t2 = threading.Thread(target=run2)
    t3 = threading.Thread(target=run3)
    l1 = threading.Lock()
    l2 = threading.Lock()
    l3 = threading.Lock()
    # 实例化三把锁

    l2.acquire()
    l3.acquire()

    t1.start()
    t2.start()
    t3.start()

你可能感兴趣的:(多进程和多线程python)