java - 以下代码中的同步有什么问题

标签 java synchronization

同步

我已经声明了一个类b,它有一个在类c中访问的同步方法:

class b {
    String msg;

    public synchronized void foo() {
        System.out.print("[" + msg);
        try {
            Thread.sleep(1000); // Threads go to sleeep

        } catch (InterruptedException e) {
            System.out.println("Caught" + e);
        }
        System.out.println("]");
    }
}

class a implements Runnable {
    b ob;

    Thread t;

    a(String msg, b obb) {
        ob = obb;
        ob.msg = msg;
        t = new Thread(this); // creating a thread
        t.start();
    }

    public void run() {
        ob.foo(); // calling method of class b
    }

    public static void main(String... a) {
        b obb = new b();
        a ob = new a("Hello", obb); /* PASSING */
        a ob1 = new a("Synch", obb); /* THE */
        a ob2 = new a("World", obb);/* MESSAGE */

        try {
            ob.t.join();
            ob1.t.join();
            ob2.t.join();
        } catch (InterruptedException e) {
            System.out.println("Caught" + e);
        }
    }
}

我期待输出:

[Hello]
[Synch]
[World]

但是代码给出:

[World]
[World]
[World]

帮我提一些建议。我是一个天真的JAVA用户。

最佳答案

使用以下代码获得预期的答案。

b类{ //字符串消息;

public void foo(String msg) {
    System.out.print("[" + msg);
    try {
        Thread.sleep(1000); // Threads go to sleeep

    } catch (InterruptedException e) {
        System.out.println("Caught" + e);
    }
    System.out.println("]");
}

}

公共(public)类 Threading 实现 Runnable {

    b ob;
String msg;
Thread t;

Threading(String message, b obb) {
    ob = obb;
    msg = message;
    t = new Thread(this); // creating a thread
    t.start();
}

public void run() {
    synchronized (ob) {
        ob.foo(msg); // calling method of class b
    }

}

public static void main(String... a) {
    b obb = new b();
    Threading ob = new Threading("Hello", obb); /* PASSING */
    Threading ob2 = new Threading("World", obb); /* THE */
    Threading ob1 = new Threading("Synch", obb);/* MESSAGE */

    try {
        ob.t.join();
        ob1.t.join();
        ob2.t.join();
    } catch (InterruptedException e) {
        System.out.println("Caught" + e);
    }
}

}

关于java - 以下代码中的同步有什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19314117/

相关文章:

mysql - 同步 Access DB 和 MySQL

java - 静态方法参数的同步

java - JEE : how to pass parameter to an interceptor

java - 迭代 LinkedHashSet 时跳过同步并且未完成删除?

java - 查找在 ListView 中单击了哪一行

java - 如何正确使用我的值作为 JComboBox.setModel() 的参数?

multithreading - 托管 C++ 中的 C# 的 lock()

c++ - 将线程的日志数据转储到公共(public)缓冲区

java - 在java中访问内部类中的变量

java - 将图标从 jbutton move 到 jbutton