使用多个线程修改groovy中的矩阵

时间:2017-11-07 10:20:38

标签: multithreading matrix groovy

我有一个多线程问题,我应该将2个随机矩阵相乘。问题是,在我完成执行后,矩阵是空的,但如果我打印插入矩阵的元素,它就会显示正确。要乘的矩阵不是空的。

import turtle
turtle.color("Red")
turtle.title("Test")
turtle.pensize(5)


def tLeft():         #Edit everything later, most likely to be inaccurate.                                   
    turtle.right(180)
    turtle.forward(10)

def tRight():
    turtle.left(180)
    turtle.forward(10)

def tUp():
    turtle.right(90)
    turtle.forward(10)

def tDown():
    turtle.left(270)
    turtle.forward(10)

turtle.onkeypress(tUp, "Up")
turtle.onkeypress(tDown, "Down")
turtle.onkeypress(tRight, "Right")
turtle.onkeypress(tLeft, "Left")    #First test: When started the code did nothing, nothing showed up and no errors was shown. Edit:only needed "listen()"
turtle.listen()

1 个答案:

答案 0 :(得分:1)

您在向我们展示的代码中错误地理解了一件大事 - 您在for循环中覆盖function Delete(ID) { var ans = confirm("Are you sure you want to delete this Record?"); if (ans) { $.ajax({ url: '@Url.Action("Delete")', data: JSON.stringify({ ID: ID }), async: true, cache: false, type: "Post", contentType: "application/json;charset=UTF-8", dataType: "json", success: function (result) { $tr.find('td').fadeOut(1000, function () { $tr.remove(); }); //alert(result); }, error: function (errormessage) { alert(errormessage.responseText); } }); } } 变量,并且在您生成所有4个线程之后,您只等待最后一个完成执行。

相反,您应该存储所有衍生线程的列表,并且您必须在脚本的末尾加入所有线程。类似的东西:

thread

您可以在脚本的最后看到它:

def queue = []
int tn = 0

for (int i = 1; i < threads + 1; i++) {
    start = taskArray[i - 1]
    stop = taskArray[i]

    def thread = Thread.start {
        for (int job = start; job < stop; job++) { //line for matrix1
            int sum = 0
            for (int j = 0; j < p1; j++) {
                for (int k = 0; k < p1; k++)
                    sum += matrix1.table[job][k] + matrix2.table[k][j]
                matrix.table[job][j] = sum
            }
        }
        tn += 1
        println "Thread " + tn + "finished"
    }

    queue << thread
}
queue*.join()
matrix.table.each { println it }

它使用Groovy的扩展运算符为列表中收集的所有元素调用queue*.join() 方法。我们使用左移运算符将每个生成的线程添加到join()列表:

queue

这相当于queue << thread

我已使用queue.add(thread)p1=16运行您的程序并应用了这些更改,我得到了类似的输出:

p2=16

希望它有所帮助。