Python 3——线程相关操作基本代码

简介: 一,创建线程''''' 功能:输出当前时间 ''' def gettime(): localtime = time.localtime(time.time()) year = localtime[0] month = localtime...


一,创建线程


''''' 
    功能:输出当前时间 
'''  
def gettime():  
    localtime = time.localtime(time.time())  
    year = localtime[0]  
    month = localtime[1]  
    day = localtime[2]  
    hour = localtime[3]  
    minute = localtime[4]  
    print("本地时间为:" + str(year) + '-' + str(month) + "-" + str(day) + " " + str(hour) + ":" + str(minute))  
  
#线程类  
class testThread(threading.Thread):  
    def __init__(self, threadname):  
        threading.Thread.__init__(self)  
        self.name=threadname  
  
    def run(self):  
        gettime()  
  
  
t1 = testThread("test1")  
t1.start()  
t1.join()  


ps:我用的是python 3.6,之前的版本,可能写法上不是threading这种,是_thread这种。

二,共享数据访问


#!/usr/bin/python3
# -*- coding: utf-8 -*-



import threading
import  time


count = 0
threadLock = threading.Lock()
class AddThread(threading.Thread):
    def __init__(self, threadname):
        threading.Thread.__init__(self)
    def run(self):
        global count
        for i in range(0, 100000):
            threadLock.acquire()
            count = count + 1
            threadLock.release()


t1 = AddThread("t1")
t2 = AddThread("t2")
t1.start()
t2.start()
t1.join()
t2.join()
print (str(count))










目录
相关文章
|
7天前
|
Python
以下是一些常用的图表类型及其Python代码示例,使用Matplotlib和Seaborn库。
以下是一些常用的图表类型及其Python代码示例,使用Matplotlib和Seaborn库。
|
2天前
|
数据安全/隐私保护 Python
探索Python中的装饰器:简化代码,提升效率
【9月更文挑战第32天】在Python编程世界中,装饰器是一个强大的工具,它允许我们在不改变函数源代码的情况下增加函数的功能。本文将通过直观的例子和代码片段,引导你理解装饰器的概念、使用方法及其背后的魔法,旨在帮助你写出更加优雅且高效的代码。
|
1天前
|
大数据 Python
Python 高级编程:深入探索高级代码实践
本文深入探讨了Python的四大高级特性:装饰器、生成器、上下文管理器及并发与并行编程。通过装饰器,我们能够在不改动原函数的基础上增添功能;生成器允许按需生成值,优化处理大数据;上下文管理器确保资源被妥善管理和释放;多线程等技术则助力高效完成并发任务。本文通过具体代码实例详细解析这些特性的应用方法,帮助读者提升Python编程水平。
18 5
|
6天前
|
Python
? Python 装饰器入门:让代码更灵活和可维护
? Python 装饰器入门:让代码更灵活和可维护
12 4
|
6天前
|
缓存 测试技术 Python
探索Python中的装饰器:简化代码,提高可读性
【9月更文挑战第28天】在Python编程中,装饰器是一个强大的工具,它允许我们在不修改原有函数代码的情况下增加额外的功能。本文将深入探讨装饰器的概念、使用方法及其在实际项目中的应用,帮助读者理解并运用装饰器来优化和提升代码的效率与可读性。通过具体示例,我们将展示如何创建自定义装饰器以及如何利用它们简化日常的编程任务。
11 3
|
5天前
|
机器学习/深度学习 数据格式 Python
将特征向量转化为Python代码
将特征向量转化为Python代码
12 1
|
7天前
|
Python
Python 装饰器入门:让代码更灵活和可维护
Python 装饰器入门:让代码更灵活和可维护
12 1
|
8天前
|
Python
5-19|记录Python调用salt代码
5-19|记录Python调用salt代码
|
5天前
|
数据采集 Linux 调度
Python之多线程与多进程
Python之多线程与多进程
12 0
|
6天前
|
并行计算 关系型数据库 MySQL
30天拿下Python之使用多线程
30天拿下Python之使用多线程
17 0
下一篇
无影云桌面