简体   繁体   English

java多线程——如何同步

[英]java multi threading - how to synchronise

I have a class with following method我有一个具有以下方法的课程

public class Test {
    private List l1;
    public void send() {
         for (<type> x : l1) {
               //send to receivers and put a log in DB
          }
    }
}

This Test class is used by different threads which will fill the variable 'l1' with their own data and send them to receivers.这个 Test 类由不同的线程使用,它们将用自己的数据填充变量“l1”并将它们发送给接收器。 If I have to synchronize this to send data sequentially so that receivers get one full frame of data every time(without jumbling of data from different threads), should I synchronize on 'l1' or synchronize on the class Test.如果我必须同步它以按顺序发送数据,以便接收者每次都获得一整帧数据(不会混淆来自不同线程的数据),我应该在“l1”上同步还是在类 Test.txt 上同步? I read the tutorials and samples but I still have this question.我阅读了教程和示例,但我仍然有这个问题。

You should synchronize on the object that represents you "shared state" (l1 in this case);您应该在代表您“共享状态”的对象上进行同步(在本例中为 l1); you must ensure that every insert/read operation is synchronized so you must have a synchronized(l1) {...} block for add (and remove ) call and one while sending:您必须确保每个插入/读取操作都是同步的,因此您必须有一个synchronized(l1) {...}块用于add (和remove )调用,并且在发送时有一个:

public void send() {
     synchronized(l1) {
         for (<type> x : l1) {
           //send to receivers and put a log in DB
         }
     }
}

depending on you requirements you can also implement something more complex like:根据您的要求,您还可以实现更复杂的东西,例如:

public void send() {
     synchronized(l1) {
         List l2=new ArrayList(l1);
         //clear l1?
     }
     for (<type> x : l2) {
        //send to receivers and put a log in DB
     }
}

and allow a grater degree of concurrency并允许更高程度的并发

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

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