java - java中的多线程程序

标签 java multithreading

我的代码出问题了。

我的代码在 Hoge 类的 setStr 中抛出 IllegalMonitorStateException

我在setStr中将Hoge.class改成了this。我的代码正确完成了!

但是为什么正常结束呢?

    public class Sample {
        static Hoge gh = new Hoge();
        static Hoge gh2 = new Hoge();

        public static void main(String[] args) {

            new Thread() {
                private Hoge h2 = gh;
                public void run() {

                    System.out.println("start initialize");
                    h2.setStr("BazzBazz");
                    System.out.println("end   initialize");

                    System.out.println("start thread 1");
                    System.out.println(h2.getStr("thread-1"));
                    System.out.println("end   thread 1");
                }
            }.start();

            new Thread() {
                private Hoge h2 = gh2;

                public void run() {
                    System.out.println("start thread 2");
                    System.out.println(h2.getStr("thread-2"));
                    System.out.println("end   thread 2");
                }
            }.start();
        }
    }

    class Hoge {
        private String fuga = "fugafuga";

        public void setStr(String str) {
            synchronized(Hoge.class) { //<-HERE ! change "Hoge.class" into "this".
                fuga = str;
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        String getStr(String suffix) {
            synchronized(Hoge.class) {
                return suffix+ fuga;
            }
        }
    }

最佳答案

您的setStr 方法应该是这样的:

public void setStr(String str) {
            synchronized(Hoge.class) { //<-HERE ! change "Hoge.class" into "this".
                fuga = str;
                try {
                    Hoge.class.wait();//call wait on Hoge.class 
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

您应该使用 Hoge.clas.wait() 而不是 wait()。为什么?
因为 ,如 oracle documentation about wait() 中所述:

This method should only be called by a thread that is the owner of this object's monitor.

线程在拥有该对象的锁之前不能对该对象调用等待。否则它会抛出 IllegalMonitorStateException .在这里,您正在获取对 Hoge(即 Hoge.class)的 Class 对象的锁定,称为 class level lock ,但正在调用 wait Hoge(this) 的当前对象。所以它导致 IllegalMonitorStateException。这就是为什么当您获取当前对象 (this) 的锁时您的代码工作正常的原因,因为在这种情况下 wait() 是在当前对象 (this) 上调用的) 本身。

关于java - java中的多线程程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15584854/

相关文章:

python - 并行目录遍历 python

线程中的 Java 异常 "main"java.lang.StackOverflowError

java - Spring原型(prototype)转为单例并在另一个类中获取值

java - JSP/javabean/servlet MVC

java - while循环和线程的无限循环问题

c++ - 使用多个线程的并行 vector 乘法比顺序 vector 乘法花费更长的时间

java - 您在构建 Web 应用程序的开发框架和工具方面有哪些经验?

java - 使用 JComboBox 更新 JDialog 中的 JPanel 时出现问题

vb.net - WaitOne()函数的正确用法是什么

c# - 我不了解 volatile 和 Memory-Barrier 的是