简体   繁体   English

Java互斥

[英]Java mutual exclusion

i just have a quick question about concurrent programming in Java. 我只是有一个关于Java并发编程的快速问题。 for example, i have a NxN matrix, and there is a corresponding thread for each row of the matrix, if there is no interaction between threads in each row, is it safe (or correct) if multiple threads access and modify separate rows of the matrix simultaneously? 例如,我有一个NxN矩阵,并且矩阵的每一行都有一个对应的线程,如果每一行中的线程之间没有交互,那么如果多个线程访问并修改该行的单独行是否安全(或正确)?同时矩阵? Thanks!! 谢谢!!

If you are only doing reads of the matrix, it is always safe. 如果仅读取矩阵,则始终是安全的。 If you are doing writes, but a thread only reads and writes to the row it is assigned, it is safe. 如果您正在执行写操作,但是一个线程仅对其分配的行进行读写操作,这是安全的。 It is only if you have a thread reading from a cell written by another thread that you have to worry about locks. 只有当您从另一个线程编写的单元中读取线程时,才需要担心锁。

If you have a native 2d array, and not a wrapper class, then concurrent row access should be fine. 如果您有一个本地2d数组,而不是包装器类,那么并发行访问应该没问题。 As long as you never read/write or write/write to the same memory location, you're okay. 只要您从不读/写或写/写到相同的内存位置,就可以了。

如果可以保证没有线程会改变任何其他线程读取或变异的元素,并且也没有线程会改变矩阵的尺寸,那么这是安全的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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