Question about threads and locks

Now I am trying to learn more about the java thread, and I have a small question that I cannot find a direct answer anywhere. Suppose I have two threads that share an object:

public class FooA implements Runnable
{
    Object data;

    public FooA(final Object newData)
    {
        data = newData;
    }

    public void doSomething()
    {
        synchronized(data)
        {
            data = new Integer(1);
        }
    }

    public void run() {
        // Does stuff
    }
}

public class FooB implements Runnable
{
    Object data;

    public FooB(final Object newData)
    {
        data = newData;
    }

    public void doSomething()
    {
        synchronized(data)
        {
            System.out.println(data);
        }
    }
}

Will FooA block FooB when it is in the doSomething section of code? Or vice versa? The feeling of my feeling says yes, but according to the book I read, it says no. Hence the need for monitoring objects. I made a slightly more complicated version of this, and everything worked fine.

I looked around a bit, but could not find a specific answer.

+3
source share
6 answers

, data. data, . , .

+2

.

-, synchronized(data) , , data . , .

, data , ( ).

final . . , , concurrency, , .

, .

concurrency . , , , .

: http://www.javaconcurrencyinpractice.com/

+3

, (.. , , - ). ?

FooB , FooA ( , FooB , FooA ).

AtomicReference, , , , .

+1

Java- .

FooA FooB , "" , .

  Object data;

, FooA, FooB, , - , .

+1

fooA.data fooB.data , - , :

Object o = new Object();
FooA fooA = new FooA(o);
FooB fooB = new FooB(o);

, , .

FooA new Integer(1) data, , . , :

fooB.data = fooA.data;

, .

Also, something you need to know about streaming is that even if everything works once, it does not mean that your program is correct or that it will work every time. Problems with threads arise only when the time works correctly (or somehow incorrectly).

+1
source

That's right, if you need to synchronize the same object, but since one thread modifies the object referenced by "data", you will need to synchronize with "this".

0
source

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


All Articles