简体   繁体   中英

Android Python Multiple Threads

Hello I am having issues in regards to running threads in Android with Python SL4A. I am trying to run two threads at the same time, but seem to be having issues

from threading import *
import time
def func1():
    while True:
        print("func1")

def func2():
    while True:
        print("func2")


thread = Thread(target = func1)
thread.start()
for i in range(1000):
    thread = Thread(target = func2)
    thread.start()
    time.sleep(2)
time.sleep(2)

the first thread func1 starts fine but then is never run again once func2 takes over.

Would anyone have any advice on how to fix this?

Thank you

I'm not sure what you're expecting here. You first pass func1 into a thread, then start it. You never reference func1 or the thread again after that.

Later, you create an iterator, within which you pass func2 into a new thread and start it. You repeat that process a thousand times, with a two second sleep between each.

Do you want both functions to run a thousand times? If so...

thread1 = Thread(target=func1)
thread2 = Thread(target=func2)

for i in range(1000):
    thread1.start()
    thread2.start()
    time.sleep(2)

Note that in your code the variable thread is assigned Thread(target=func1) before the iterator. Inside the iterator, the same name, thread , is assigned Thread(target=func2) , so it no longer points to the same thing.

Also, if you're creating an object to reference it in a loop, you want to try and keep the initialisation outside of the loop, so you don't create the same object over and over. Just create one, then reference it in the loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM