一,创建线程
''''' 功能:输出当前时间 ''' 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))