Python多线程多进程问题

新手求问,刚学习python,发现在两个线程或两个进程开启后(都有一个while循环),必须要第一个执行完成,第二个才会执行,求问为什么会这样

 import threading
import time

class Test:
    def run(self):
        threading.Thread(target=self.func1()).start()
        threading.Thread(target=self.func2()).start()

    def func1(self):
        count = 0
        while count < 3:
            print("thread1")
            count += 1
            time.sleep(2)

    def func2(self):
        count = 0
        while count < 3:
            print("thread2")
            count += 1
            time.sleep(1)


if __name__ == "__main__":
    Test().run()
 import multiprocessing
import time

class Test:
    def run(self):
        multiprocessing.Process(target=self.func1()).start()
        multiprocessing.Process(target=self.func2()).start()

    def func1(self):
        count = 0
        while count < 3:
            print("thread1")
            count += 1
            time.sleep(2)

    def func2(self):
        count = 0
        while count < 3:
            print("thread2")
            count += 1
            time.sleep(1)


if __name__ == "__main__":
    Test().run()

执行结果:

 thread1
thread1
thread1
thread2
thread2
thread2

你在函数传参时后面加了小括号就成函数调用了不是把函数当做参数传参
正确的代码:
import threading
import time

class Test:
def run(self):
threading.Thread(target=self.func1).start()
threading.Thread(target=self.func2).start()

def func1(self):
    count = 0
    while count < 3:
        print("thread1")
        count += 1
        time.sleep(2)

def func2(self):
    count = 0
    while count < 3:
        print("thread2")
        count += 1
        time.sleep(1)

if name == "__main__":
Test().run()

import multiprocessing
import time

class Test:
def run(self):
multiprocessing.Process(target=self.func1).start()
multiprocessing.Process(target=self.func2).start()

def func1(self):
    count = 0
    while count < 3:
        print("thread1")
        count += 1
        time.sleep(2)

def func2(self):
    count = 0
    while count < 3:
        print("thread2")
        count += 1
        time.sleep(1)

if name == "__main__":
Test().run()

你启动的是进程,而且是阻塞的方式 而不是异步的方式。

开启异步线程执行,也许会好些

你打码写错了
def run(self):
multiprocessing.Process(target=self.func1()).start()
multiprocessing.Process(target=self.func2()).start()
multiprocessing.Process里面的target参数要求的是你要传入一个函数而你传入的是一个函数的返回值 而你这两个函数没有返回值所以默认为None所以你的多进程是没有启动的

def run(self):
threading.Thread(target=self.func1()).start()
threading.Thread(target=self.func2()).start()

这个地方写错了,threading.Thread() 中 target 接受的是函数名,
你写的 target=self.func1() 实际上是先求的 self.func1() 这个函数的值,
所以你看到了 thread1、thread1、thread1 的输出,
而你的函数 self.func1() 没有返回值,所以你这相当于创建了 threading.Thread(target=None).start() 这样一个线程,这个线程未被执行。
第二个线程和第一个一样,都是执行了你的函数,创建了一个空线程。

threading.Thread(target=self.func1()).start()
threading.Thread(target=self.func2()).start()
这两行中func1()和func2()的()去掉即可,target传入的参数要的是函数名而不是函数调用,即改成:
threading.Thread(target=self.func1).start()
threading.Thread(target=self.func2).start()