python启动线程的方法

# coding:utf-8
import threading
import time
#方法二:从Thread继承,并重写run()
class MyThread(threading.Thread):
    def __init__(self,arg):
        super(MyThread, self).__init__()#注意:一定要显式的调用父类的初始化函数。
        self.arg=arg
    def run(self):#定义每个线程要运行的函数
        time.sleep(self.arg)
        print ('the arg is:%s\r\n' % self.arg)

for i in range(4):
    t =MyThread(i)
    t.start()

print ('main thread end!')
# coding:utf-8
import threading
import time
#方法一:将要执行的方法作为参数传给Thread的构造方法
def action(arg):
    time.sleep(arg)
    if(arg==1):
        print( 'the arg is:%s\r\n' %arg)
    if(arg==2):
        print('work2\r\n')
    if(arg==3):
        print('work3\r\n')

for i in range(4):
    t =threading.Thread(target=action,args=(i,))
    t.start()

print( 'main thread end!')

获取线程名字

# coding:utf-8
import threading
import time

def action(arg):
    time.sleep(1)
    print  ('sub thread start!the thread name is:%s\r' % threading.currentThread().getName())
    print ('the arg is:%s\r\n' %arg)
    time.sleep(1)

for i in range(4):
    t =threading.Thread(target=action,args=(i,))
    t.start()

print ('main_thread end!')
#coding:utf-8
import threading
import time

def action(arg):
    time.sleep(1)
    print  ('sub thread start!the thread name is:%s   \r\n ' % threading.currentThread().getName())
    print( 'the arg is:%s\r\n '  %arg)


thread_list = []    #线程存放列表
for i in range(4):
    t =threading.Thread(target=action,args=(i,))
    t.setDaemon(True)
    thread_list.append(t)

for t in thread_list:
    t.start()

for t in thread_list:
    t.join()
print( 'the main is end ')

消费者生产者模式

# encoding: UTF-8
import threading
import time

# 商品
product = None
# 条件变量
con = threading.Condition()

# 生产者方法
def produce():
    global product
    if con.acquire():
        while True:
            if product is None:
                print ( 'produce...')
                product = 'anything'
                # 通知消费者,商品已经生产
                con.notify()
            # 等待通知
            con.wait()
            time.sleep(2)


# 消费者方法
def consume():
    global product
    if con.acquire():
        while True:
            if product is not None:
                print ('consume...')
                product = None
                # 通知生产者,商品已经没了
                con.notify()
            # 等待通知
            con.wait()
            time.sleep(2)
t1 = threading.Thread(target=produce)
t2 = threading.Thread(target=consume)
t2.start()
t1.start()

例子来之:https://www.cnblogs.com/tkqasn/p/5700281.html

python--threading多线程总结

猜你喜欢

转载自blog.csdn.net/forcoin/article/details/81351417