引入线程包或者命名空间import threading

一:建立一个简单的线程程序

import time, threading

def test():
    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('thread %s ended.' % threading.current_thread().name)

print('thread %s is running...' % threading.current_thread().name)
t = threading.Thread(target=test, name='test')
t.start()
t.join()
print('thread %s ended.' % threading.current_thread().name)

运行结果如下:

#-*- encoding: gb2312 -*-
import string, threading, time
 
def thread_main(a):
  global count, mutex
  # 获得线程名
  threadname = threading.currentThread().getName()
 
  for x in xrange(0, int(a)):
    # 取得锁
    mutex.acquire()
    count = count + 1
    # 释放锁
    mutex.release()
    print(threadname, x, count)
    time.sleep(1)
 
def main(num):
  global count, mutex
  threads = []
 
  count = 1
  # 创建一个锁
  mutex = threading.Lock()
  # 先创建线程对象
  for x in xrange(0, num):
    threads.append(threading.Thread(target=thread_main, args=(10,)))
  # 启动所有线程
  for t in threads:
    t.start()
  # 主线程中等待所有子线程退出
  for t in threads:
    t.join()
 
if __name__ == '__main__':
  num = 4
  # 创建4个线程
  main(4)

相关理解:

如何理解join()方法:使得一个线程可以等待另一个线程执行结束后再继续运行。这个方法还可以设定一个timeout参数, 通俗一点说就是让当前操作join方法的线程先完成,再去执行其它流程,timeout是超时时间,比如join(1),如果过了1s线程没有结束,线程会自动结束

如何理解线程同步:当系统中对同一个变量或方法同一时刻只允许被一个动作占用时,就要采用线程同步的方案去处理了

最新文章

  1. adv
  2. javascript数据结构与算法---列表
  3. Webservice接口
  4. LNMP环境搭建
  5. Android http超时选项的测试
  6. SVN中的常见错误(长期更新)
  7. shell 获取cpu使用率
  8. Ubuntu中安装DiscuzX2
  9. Jar mismatch! Fix your dependencies的问题(转)
  10. EasyUI篇の日期控件
  11. HTML&amp;CSS基础学习笔记1.12—引入样式表
  12. APP中的 H5和原生页面如何分辨、何时使用
  13. 在ASP.NET 中检测手机浏览器(转)
  14. CMake--变量
  15. Linux下查看80端口是否被占用
  16. css3中trastion,transform,animation基本的了解
  17. 利用django信号实现计数功能
  18. laravel中db获取某个数据的具体字段值:
  19. Invocation of init method failed; nested exception is java.text.ParseException: &#39;?&#39; can only be specfied for Day-of-Month or Day-of-Week.
  20. GIRDVIEW 控件绑定数据后 后台c#控制隐藏某列

热门文章

  1. PAT 天梯赛 L1-022. 奇偶分家 【水】
  2. Codeforces Round #397 by Kaspersky Lab and Barcelona Bootcamp (Div. 1 + Div. 2 combined) E. Tree Folding
  3. JMS、MQ、ActiveMQ
  4. pycharm中创建并设置docker解释器
  5. 20145222黄亚奇《网络对抗》web安全基础实践
  6. 周立功CAN-II引脚图
  7. QMesageBox的使用
  8. Android中APK安装过程及原理解析
  9. apache kafka配置中request.required.acks含义
  10. CTCS-2017滚粗记