PYTHON 中相同 sleep() 时间的随机变量总和

Sum of Random variables in same sleep() time in PYTHON

如果A和B同时来,我想计算数字的总和。你能帮助我吗? 我的代码在这里:

import threading
import time
import random


def print_hello():
    for i in range(6):
        time.sleep(1)
        print("A :" + str(random.randrange(1,20)) + "\n")


def print_hi():
    for i in range(6):
        time.sleep(1.5)
        print("B :" + str(random.randrange(1,10)))




t1 = threading.Thread(target=print_hello)
t2 = threading.Thread(target=print_hi)
t1.start()
t2.start()

if A and B come same time 是什么意思?

如果你只想在同一秒打印数字时求和,

import time
import random

randomA = 0
randomB = 0
timeA = int(time.time()%60)
timeB = int(time.time()%60)

def print_hello():
    for i in range(6):
        time.sleep(1)
        global timeA
        timeA = int(time.time()%60)
        global randomA
        randomA = random.randrange(1,20)
        print('[A] TimeA',timeA,'TimeB',timeB,' B=',randomB)
        print("A :" + str(randomA))
        if(timeA == timeB):
            print("Times match. Sum = ",str(randomA+randomB))


def print_hi():
    for i in range(6):
        time.sleep(1.5)
        global timeB
        timeB = int(time.time()%60)
        global randomB
        randomB = random.randrange(1,20)
        print('[B] TimeA',timeA,'TimeB',timeB,' A=',randomA)
        print("B :" + str(randomB))
        if(timeA == timeB):
            print("Times match. Sum = ",str(randomA+randomB))



t1 = threading.Thread(target=print_hello)
t2 = threading.Thread(target=print_hi)
t1.start()
t2.start()