java同步问题

Mo *_*o . 2 java multithreading volatile synchronized

我遇到的问题是Synchronized不按我期望的方式行事,我也尝试使用volatile关键字:

共享对象:


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;
}
}
Run Code Online (Sandbox Code Playgroud)

线程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();
    }
    }
}
Run Code Online (Sandbox Code Playgroud)

线程2:


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

    }
    public void run() {
    for (int i = 0; i  10; i++) {
       v.setValue( "libya", "awesome" );
       System.out.println("In Libya Thread " + v.getValue() );

    }
    }
}

Run Code Online (Sandbox Code Playgroud)

通话类:


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();

    }
}
Run Code Online (Sandbox Code Playgroud)

偶尔我会得到"在利比亚线程刚果酷",这应该永远不会发生.我只期望:"在利比亚线程利比亚真棒""在刚果线程刚果酷"

我不希望他们混在一起.

Dar*_*roy 5

呼叫可以像下面这样交错:

Thread 1 : v.setValue()
Thread 2 : v.setValue()
Thread 1 : v.getValue() // thread 1 sees thread 2's value
Thread 2 : v.getValue() // thread 2 sees thread 2's value
Run Code Online (Sandbox Code Playgroud)