python多线程实例

3 篇文章 0 订阅
2 篇文章 0 订阅

多线程 

Thread是线程类,有两种使用方法,直接传入要运行的方法或

1.从Thread继承并覆盖run()

import threading
import time
class MyThread(threading.Thread):
    def __init__(self, n):
        super(MyThread, self).__init__()
        self.n = n
    def run(self):
        print("runnint task", self.n)
t1 = MyThread("t1")
t2 = MyThread("t2")
t1.start()  # runnint task t1
#t1.join()
t2.start()  # runnint task t2
#t2.join()

1.当用继承的方式去创建线程时,一定要重写父类的Run()方法
2.当线程的run()方法结束的时候,线程也结束
3.我们认为是无法完全控制线程的,但是我们可以通过一些方式来影响线程的调用
4.线程的几种状态 新建----就绪----运行-----死亡 等待(阻塞)主要出现就绪与运行之间

5.在UNIX平台上,当某个进程终结之后,该进程需要被其父进程调用wait,否则进程成为僵尸进程(Zombie)。所以,有必要对每个Process对象调用join()方法 (实际上等同于wait)。对于多线程来说,由于只有一个进程,所以不存在此必要性。

2.直接传入要运行的方法

"""
例1:
# 假定这是你的银行存款:
balance = 0
lock = threading.Lock()
def change_it(n):
    # 先存后取,结果应该为0:
    global balance
    balance = balance + n
    balance = balance - n

def run_thread(n):
    #lock = threading.Lock()
    global lock
    for i in range(100000):
        lock.acquire()
        try:
            # 放心地改吧:
            change_it(n)
        finally:
            # 改完了一定要释放锁:
            lock.release():
t1 = threading.Thread(target=run_thread, args=(5,))
t2 = threading.Thread(target=run_thread, args=(8,))
t1.start()
t2.start()
#t1.join()
#t2.join()
print balance

例2:
#新线程执行的代码:
def loop(fn,a,b):
    print fn,a,b
    print 'thread %s is running...',threading.current_thread().name
    n = 0
    while n < 5:
        n = n + 1
        print "thread %s>>>%s",threading.current_thread().name,n
        time.sleep(1)
    print "thrad %s end",threading.current_thread().name
print "thread %s is running...",threading.current_thread().name
filename = "tgets.csv"
t = threading.Thread(target=loop,name="LoopThread",args=(filename,5,5))
t.start()
t.join()
print "thread %s ended.",threading.current_thread().name

例3:
hehe=6
def f():
    global hehe
    print(hehe)
    hehe=3
f()
print(hehe)
"""

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小金子的夏天

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值