from threading import Thread
import time
class myThreadClass(Thread):
def __init__(self):
Thread.__init__(self)
self.myVariable = 0
print ('Value of myVariable is: %d')%self.myVariable#Initial value
self.daemon = False
print 'Starting Child thread.\n'
self.start()
def run(self):
k = 1
for i in range(0,5):
self.myVariable = self.myVariable+k #Increment the value and assign
print ('Value of self.myVariable now is: %d')%self.myVariable#Print current value
k += 1
print 'The final value of self.myVariable is: %d'%self.myVariable
print 'Child thread finished its job'
if __name__ == "__main__":
obj = myThreadClass()
time.sleep(2)
print 'This is the main thread. The value of self.myVariable is: %d'%obj.myVariable
控制台输出为:
Value of myVariable is: 0
Starting Child thread.
Value of myVariable now is: 1
Value of myVariable now is: 3
Value of myVariable now is: 6
Value of myVariable now is: 10
Value of myVariable now is: 15
The final value of self.myVariable is: 15
Child thread finshed its job
This is the main thread. The value of myVariable is: 15
我建议你像这样创建你的线程类
根据我对你问题的理解。我已经创建了一个代码片段,在猜测了您真正想要做什么之后。你知道吗
下面的代码段在名为
myThreadClass()
的类中运行一个线程。此类的__init__()
中有一个名为self.myVariable
的变量。在run()
中,为了演示的目的,self.myVariable
的值被增加/修改。之后self.myVariable
的值从myThreadClass()
本身打印出来,之后也从main()
打印出来。你知道吗控制台输出为:
这是你要的吗?你知道吗
相关问题 更多 >
编程相关推荐