简体   繁体   English

为什么这个同步语句示例不起作用?

[英]Why isn't this synchronized statement example working?

Playing with synchronization, I basically have two cuncurrent threads executing a method of the same object, but probably I'm getting something wrong. 使用同步,我基本上有两个执行相同对象的方法的cuncurrent线程,但可能我遇到了错误。

Given this piece of code 鉴于这段代码

public class Test {
    public static void main(String... args) throws InterruptedException{
        new Test();
    }

    Test() throws InterruptedException{

        Stuff s = new Stuff();

        Th t1 = new Th(1,s);
        Th t2 = new Th(2,s);

        t1.start();
        Thread.sleep(1000);
        t2.start();
    }
}

class Stuff{
    public Integer count=0;

    void doStuff(int threadId){
        System.out.println(threadId + ": in doStuff");
        synchronized (count) {
            count += 100;

            if (threadId == 1) {
                try {Thread.sleep(3000);} 
                catch (InterruptedException e) {e.printStackTrace();}
            }

            System.out.println(threadId + ": count = " + count);
        }
    }
}

class Th extends Thread{

    public Stuff s;
    public int id;

    @Override
    public void run(){
        System.out.println(id+": thread run");
        s.doStuff(id);
    }

    Th(int id_,Stuff s_){
        s=s_;
        id=id_;
        System.out.println(id+": thread created");
    }
}

I get this output 我得到了这个输出

1: thread created
    2: thread created
    1: thread run
    1: in doStuff
    2: thread run
    2: in doStuff
    2: count = 200
    1: count = 200

Why is t1 printing "200"? 为什么t1打印“200”? Shouldn't t2 wait for t1 to execute the synchronized block before being able to get the lock on count and then execute the block? 在能够获得锁定count然后执行块之前, t2不应该等待t1执行同步块吗?

 synchronized (count) {
        count += 100;

That does not work. 这不起作用。

You are synchronizing on Objects, not on variables or fields. 您正在同步对象,而不是变量或字段。

Every time you increase the count , that field will point at a different Integer object. 每次增加count ,该字段将指向不同的Integer对象。 So your synchronized block uses a different monitor all the time. 因此,您的synchronized块始终使用不同的监视器。

You need to find a "stable" lock object, for example 例如,您需要找到“稳定”的锁定对象

 private final Object lockMonitor = new Object();

(then you can say synchronized (lockMonitor){} instead) (然后你可以说synchronized (lockMonitor){}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM