Java sync and threads

I am having problems with Synchronized that do not behave as I expect, I also tried using the volatile keyword:

Common object:

public class ThreadValue {

    private String caller;
    private String value;

    public ThreadValue( String caller, String value ) {
        this.value = value;
        this.caller = caller;
    }

    public synchronized String getValue() {
        return this.caller + "     "  + this.value;
    }
    public synchronized void setValue( String caller, String value ) {
        this.caller = caller;
        this.value = value;
    }
}

Theme 1:

class CongoThread implements Runnable {
    private ThreadValue v;
    public CongoThread(ThreadValue v) {
        this.v = v;
    }
    public void run() {
        for (int i = 0; i < 10; i++) {
            v.setValue( "congo", "cool" );
            v.getValue();
        }
    }
}

Theme 2:

class CongoThread implements Runnable {
    private ThreadValue v;
    public CongoThread(ThreadValue v) {
    this.v = v;

    }
    public void run() {
        for (int i = 0; i < 10; i++) {
            v.setValue( "congo", "lame" );
            v.getValue();
        }
    }
}

Call Class:

class TwoThreadsTest {
    public static void main (String args[]) {

        ThreadValue v = new ThreadValue("", "");
        Thread congo = new Thread( new CongoThread( v ) );
        Thread libya = new Thread( new LibyaThread( v ) );

        libya.start();
        congo.start();
    }
}

Sometimes I get "In Libya Thread congo cool" what should never have happened. I expect only:
"In Libya Thread libya awesome"
"In Congo Thread congo cool"

I do not expect them to be mixed.

-2
source share
3 answers

What happens is the following:

  • Stream 1 is set to
  • Stream 2 is set to
  • In stream 1, the value specified by stream 2 is read.

, 1 , get/set . - , , get. . . . .

: , !

Object lockObject = new Object();
Thread t1 = new CongroThread(v, lockObject);
Thread t2 = new LibyaThread(v, lockObject);

...

class CongoThread implements Runnable {
    private ThreadValue v;
    private Object lockObject;

    public CongoThread(ThreadValue v, Object lockObject) {
    this.v = v;
    this.lockObject = lockObject,
    }
    public void run() {
        for (int i = 0; i < 10; i++) {
            synchronized(lockObject)
            {
                v.setValue( "congo", "lame" );
                v.getValue();
            }
        }
    }
}
+1

getValue setValue ,

v.setValue( "congo", ..);
v.getValue();

, , 1 setValue getValue

+1

System.out.print? , .

synchronzied(System.out) {
    System.out.print(....);
    System.out.flush();
}
0

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


All Articles