zoukankan      html  css  js  c++  java
  • python threading acquire release

    线程同步

    //test.py

    import threading

    import time

    exitFlag = 0

    class myThread (threading.Thread):

        def __init__(self, threadID, name, counter):

            threading.Thread.__init__(self)

            self.threadID = threadID

            self.name = name

            self.counter = counter

        def run(self):

            print "Starting " + self.name

            threadLock.acquire()

            print_time(self.name, self.counter, 5)

            threadLock.release()

            print "Exiting " + self.name

    def print_time(threadName, delay, counter):

        while counter:

            if exitFlag:

                    #threading.Thread.exit()

                    return

            time.sleep(delay)

            print "%s: %s" % (threadName, time.ctime(time.time()))

            counter -= 1

    threadLock = threading.Lock()

    threads = []

    thread1 = myThread(1, "Thread-1", 1)

    thread2 = myThread(2, "Thread-2", 2)

    thread1.start()

    thread2.start()

    #exitFlag = 1

    threads.append(thread1)

    threads.append(thread2)

    for t in threads:

            t.join()

    print "Exiting Main Thread"

    //result

    # python test.py
    Starting Thread-1
    Starting Thread-2
    Thread-2: Wed Nov 15 18:31:53 2017
    Thread-2: Wed Nov 15 18:31:55 2017
    Thread-2: Wed Nov 15 18:31:57 2017
    Thread-2: Wed Nov 15 18:31:59 2017
    Thread-2: Wed Nov 15 18:32:01 2017
    Exiting Thread-2
    Thread-1: Wed Nov 15 18:32:02 2017
    Thread-1: Wed Nov 15 18:32:03 2017
    Thread-1: Wed Nov 15 18:32:04 2017
    Thread-1: Wed Nov 15 18:32:05 2017
    Thread-1: Wed Nov 15 18:32:06 2017
    Exiting Thread-1
    Exiting Main Thread

    Finally:

    看到没有,关键任务是大家排排队,吃果果。

    不要争,不要抢,谁先干的,就让他先干完,咋这么过瘾呢!!!:):)

  • 相关阅读:
    基于alpine定制常用命令镜像
    sudo cat > EOF权限问题
    Nginx AWS ELB 域名解析后端502问题
    harbor使用aws s3存储
    Tomcat 优化和改进
    webservice 使用JaxWsDynamicClientFactory报空指针异常
    spring boot 集成 Apache CXF 调用 .NET 服务端 WebService
    eclipse launching workspace太慢的解决方法
    Remote System Explorer Operation卡死Eclipse解决方案
    同一个Tomcat 同一个端口 部署多个项目
  • 原文地址:https://www.cnblogs.com/woodzcl/p/7843096.html
Copyright © 2011-2022 走看看