题
我具有的问题同步的不行为的方式我希望,我试图使用挥发性的关键字也:
共享的对象:
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;
}
}
螺纹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();
}
}
}
螺纹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();
}
}
}
叫类:
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();
}
}
偶尔我得到 "In Libya Thread congo cool"
这应该永远不会发生。我希望只:
"In Libya Thread libya awesome"
"In Congo Thread congo cool"
我不希望他们被混合的。
解决方案
会发生什么情况是以下:
- 螺纹1套价值
- 螺纹2组价值
- 螺纹1读该价值设定的螺纹2。
为了解决这个你需要有1锁定对象卫get/set功能电话对这两个线程。最好的方式来做到这一点,是使一个额外的同步方法,并都设置并得到的。然而有时这是不可取的。在这种情况下得到两个线程的一个锁定的对象。这只是一个普通的对象。他们然后利用同步块。
执行的每个螺纹就像下面,请注意,他们需要有准确的相同的对象!
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();
}
}
}
}
其他提示
你只是同步访问分别getValue
和setValue
不是两衬
v.setValue( "congo", ..);
v.getValue();
然后,当然两个线程可以在一个的setValue
和getValue
之间交错
你synchronze是System.out.print的电话?如果不同步,它们是线程安全的,但正确的顺序可能不会发射。
synchronzied(System.out) {
System.out.print(....);
System.out.flush();
}
不隶属于 StackOverflow