创建两个线程(让我们称之为T1和T2)。 T1应打印“我是T1”,T2应打印“我是T2”。主线程(创建T1和T2的线程)应该等待它们。 o应该有一个初始化为10的共享变量x.T1应该将x增加5,T2应该将x增加100. o然后,在T1和T2完成后,主进程应该打印“我是主线程,两个线程完成“。此外,主线程应该打印x的最后一个值。
答案 0 :(得分:1)
我不确切地知道你的问题是什么,但让我试试:
这里是:
import threading
x = 10
class T1 (threading.Thread):
def __init__(self):
super(T1 , self).__init__(name="T1 thread")
print 'I am T1'
def run(self):
global x
x += 5
class T2 (threading.Thread):
def __init__(self):
super(T2 , self).__init__(name="T2 thread")
print 'I am T2'
def run(self):
global x
x += 100
t1 = T1()
t2 = T2()
t1.start()
t2.start()
while t1.is_alive() or t2.isAlive():
pass
print "t1 and t2 are done"
print x
因为您没有使用任何类型的列表或数据结构,但是如果您假装使用任何列表,行,堆栈等,请记得检查此链接。 Python Multithreaded Programming
答案 1 :(得分:0)
这应该有用。
import threading
x = 10
def prints(Text,increment):
global x
print Text
x += increment
thread1 = threading.Thread(target=prints, args=("I am T1\n",5))
thread2 = threading.Thread(target=prints, args=("I am T2\n",100)) #Create threads and pass arguments to function
thread1.start()
thread2.start() #Start threads
thread1.join() #Wait until thread1 has finished execution
thread2.join() #Wait until thread2 has finished execution
print "I am the main thread, the two threads are done"
print x
raw_input("") #Just to prevent window from closing