What will happen to the synchronized block in the thread that is inside the synchronized method?

So basically what will happen if you have the following:

class SyncTest {
    private final static List<Object> mObjectList = new ArrayList<Object>();

    public synchronized void mySyncMethod(Object object) {
        new Thread(new Runnable() {
            public void run() {
                synchronized (SyncTest.this) {
                    for (int i = 0; i < mObjectList.size(); i++) {
                        //Do something with object
                    }
                }
            }
        }).start();
    }
}
  • Let's say an action must be performed in different threads that are repeated across the collection. Therefore, why create a thread in a method with different objects.
  • Is this the right way, or perhaps the best way?
  • Does this pose any threats?
+4
source share
5 answers

. - ( ). , , . , , , , . , .

, mySyncMethod, SyncTest, , , .

, , SyncTest, , . SyncTest - ( , , mySyncMethod SyncTest, , mySyncMethod SyncTest), , . , , , .

:

  • , , , , , .

  • SyncTest , , , .

  • , SyncTest; , , , , .

, , .

+3

synchronized Thread, synchronized for.

, , , , , this . , SyncTest.this, SyncTest. mObjectList.

this , Thread , mySyncMethod .

, , Concurrent, List concurrency.

+3

, synchronization , , , - .

0

mySyncMethod() , , , SyncTest.

, synchronize , THAT SyncTest.

( , 'this' , )

0

, . .

0

Source: https://habr.com/ru/post/1540743/


All Articles