代码之家  ›  专栏  ›  技术社区  ›  hermit

显示奇怪结果的同步块

  •  0
  • hermit  · 技术社区  · 9 年前

    我正在尝试用java运行一个简单的多线程程序,该程序使用 synchronized 块。我有一节课 TestThread 它有一个字段 string 这是一个 StringBuffer 变量我创建了两个线程 one two 他们每个人 一串 变量初始化为 字符串缓冲区 b 其中包含值 A 。进入运行状态的第一个线程必须显示值 A. 一百次,然后将其递增一,以便下一个运行的线程将显示递增的值 B 也有一百次。我使用了由 this 内部 同步的,同步的 。但不幸的是,我没有得到预期的产量。第一个线程正在显示 A. 超过一百次,第二个线程正在显示 B 小于100。每次运行它,我都会得到不同的输出。所以我认为,相互排斥是没有实现的。我在这里做错了什么?

        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();
        }
        }
    
    1 回复  |  直到 9 年前
        1
  •  2
  •   TheLostMind    9 年前

    您正在锁定 当前对象 即, this 。因此,您锁定了2 不同的对象 。使用通用锁,然后尝试相同的示例。

    synchronized(this) ==> synchronized(someGlobalObject)