
#!/usr/bin/python
import time
#利用time函数,
import threading
# print ("time.time(): %s " %time.time())
# print (time.localtime( time.time() ))
# print (time.asctime( time.localtime(time.time()) ))
def loop1(in1):
print("start loop 1 at :",time.ctime())
print("in1",in1)
time.sleep(4)
print("end loop 1 at: ",time.ctime())
def loop2(in1,in2):
print("in1:",in1,"in2:",in2)
print("start loop 2 at :",time.ctime())
time.sleep(2)
print("end loop 2 at: ",time.ctime())
def main():
print("Staring at:",time.ctime())
t1 = threading.Thread(target = loop1,args = ("int1",))
t1.start()
t2 = threading.Thread(target = loop1,args = ("int1","int2"))
t2.start()
print("all done at:",time.ctime())
if __name__ == '__main__':
main()
while True:
time.sleep(1)
案例5
- #!/usr/bin/python
import time
#利用time函数,
import threading
# print ("time.time(): %s " %time.time())
# print (time.localtime( time.time() ))
# print (time.asctime( time.localtime(time.time()) ))
def loop1(in1):
print("start loop 1 at :",time.ctime())
print("in1",in1)
time.sleep(4)
print("end loop 1 at: ",time.ctime())
def loop2(in1,in2):
print("in1:",in1,"in2:",in2)
print("start loop 2 at :",time.ctime())
time.sleep(2)
print("end loop 2 at: ",time.ctime())
def main():
print("Staring at:", time.ctime())
t1 = threading.Thread(target=loop1, args=("int1",))
t1.start()
t2 = threading.Thread(target=loop2, args=("int1", "int2"))
t2.start()
print("all done at:",time.ctime())
#就是多了两个JOIN()表示等待多线程执行完成.
t1.join()
t2.join
if __name__ == '__main__':
main()
while True:
time.sleep(1)
案例6,没有主线程守护
import time
import threading
def fun():
print("start fun")
time.sleep()
print("end fun")
print ("main thread")
t1 = threading.Thread(target = fun, args =() )
t1.start()
time.sleep(1)
print("main thread end")
案例7,守护线程
import time
import threading
def fun():
print("start fun")
time.sleep()
print("end fun")
print ("main thread")
t1 = threading.Thread(target = fun, args =() )
t1.setDaemon(Ture)#这个线程对主线程进行了守护,如果主线程停止了,子线程也会跟着挂.
t1.start()
time.sleep(1)
print("main thread end")
案例8
import time
import threading
def loop1():
print("start loop 1 at :",time.ctime())
time.sleep(4)
print("end loop 1 at :", time.ctime())
def loop2():
print("start loop 2 at :",time.ctime())
time.sleep(2)
print("end loop 2 at :", time.ctime())
def loop3():
print("start loop 3 at :",time.ctime())
time.sleep(5)
print("end loop 3 at :", time.ctime())
def main():
print("Starting at :", time.timectime())
t1 = threading.Thread(target= loop1,args=())
t1.setName("THR_1")
t1.start()
t2 = threading.Thread(target= loop2,args=())
t2.setName("THR_2")
t2.start() print("Starting at :", time.timectime())
t3 = threading.Thread(target= loop3,args=())
t3.setName("THR_3")
t3.start()
time.sleep(3)
#enumerate得到正在运行的子程序,即子线程1和子线程3
for thr in threading.enumerat():
pirnt("正在运行的子线程名字是:%S"%thr.getName())
pirnt("正在运行的子线程名字是:%S"%threading.activeCount())
print("all done at:",time.ctime())
if __name __ =="__main__":
main()

案例09
