[英]synchronized block showing weird results
I am trying to run a simple multi-threaded program in java that uses a synchronized
block inside a non-static method.I have a class TestThread
which has a field string
which is a StringBuffer
variable. 我正在尝试在Java中运行一个简单的多线程程序,该程序在非静态方法中使用
synchronized
块。我有一个TestThread
类,该类的字段string
是StringBuffer
变量。 I have created two threads one
and two
and each of their string
variables initialized to StringBuffer
b
which contains the value A
. 我创建了两个线程
one
和two
,它们的每个string
变量都初始化为StringBuffer
b
,其中包含值A
The first thread that goes to running state has to display the value A
hundred times and after that increment it by one so that the next thread running will display the incremented value B
hundred times too.I have used the current object denoted by this
inside the synchronized
. 该进入行驶状态的第一个线程具有显示价值
A
百倍,之后增加它由一个使下线程运行将显示增加的值B
百倍too.I已经使用由表示当前的对象this
内部的synchronized
。 But unfortunately I am not getting the expected output. 但是不幸的是我没有得到预期的输出。 The first thread is displaying
A
more than hundred times and second thread is displaying B
less than 100. And each time I run it, I am getting different outputs.So I think that the mutual exclusion is not achieved. 第一个线程显示的
A
大于100,第二个线程显示的B
小于100。每次运行它,我得到的输出都是不同的。因此,我认为无法实现互斥。 What I am doing wrong here? 我在这里做错了什么?
public class TestThread extends Thread{
StringBuffer string;
public void run(){
synchronized(this){
for(int i=0;i<100;i++){
System.out.print(this);
}
System.out.println();
string.setCharAt(0,(char)(string.charAt(0)+1));
}
}
public TestThread(StringBuffer string){
this.string=string;
}
public String toString(){
return string.toString();
}
public static void main(String args[]){
StringBuffer b=new StringBuffer("A");
TestThread one=new TestThread(b);
TestThread two=new TestThread(b);
one.start();
two.start();
}
}
You are locking on the current object ie, this
. 您正在锁定当前对象,即
this
。 Thus you are locking on 2 different objects . 因此,您将锁定2个不同的对象 。 Use a common lock and then try the same example.
使用通用锁,然后尝试相同的示例。
synchronized(this)
==> synchronized(someGlobalObject)
synchronized(this)
==> synchronized(someGlobalObject)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.