无法从GUI线程中获取String到java中的“逻辑”线程

时间:2013-05-09 11:42:53

标签: java swing thread-safety jtextarea illegalmonitorstateexcep

我一直在编写一个程序,搜索一个数字列表,找到加起来某个其他数字的数字。没有问题,algorhythm虽然可能不是很有效,但功能正常。

现在,必须从文本文件中获取数字列表,但我一直在努力使用户可以将列表复制粘贴到TextArea中,按Enter键,然后让程序发送字符串回到正常(非GUI)线程。

为此我遵循this example(最佳答案)。我正在使用按键事件而不是按下按钮,而是使用字符串而不是链接列表,但除此之外,非常相似。

我创建和运行TextDemo的代码(是的,我改编了一个教程程序):

  /*Copy paste text in window */
  public static String copypaste() throws Exception{
    String text = "";
    final TextDemo demo = new TextDemo();
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        demo.createAndShowGUI();
      }
    });
    synchronized(demo.text){
      while(demo.text.equals("")){   //if the window is unused
        demo.text.wait();
      }
      text = demo.text;
    }
    return text;
  }

TextDemo本身(减去免责声明,请不要提醒Oracle :)):

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class TextDemo extends JPanel implements KeyListener{
    protected JTextArea textArea;
    private final static String newline = "\n";
    public String text = "";
    boolean used = false;

    public TextDemo() {
        super(new GridBagLayout());

        textArea = new JTextArea(100, 30);
        textArea.addKeyListener(this);

        textArea.setEditable(true);
        JScrollPane scrollPane = new JScrollPane(textArea);

        //Add Components to this panel.
        GridBagConstraints c = new GridBagConstraints();
        c.gridwidth = GridBagConstraints.REMAINDER;

        c.fill = GridBagConstraints.BOTH;
        c.weightx = 1.0;
        c.weighty = 1.0;
        add(scrollPane, c);
    }

    public void keyPressed(KeyEvent e) {
        // Listen for the key pressed and check it against "Enter"
        // Then read out of our textarea control and print to screen4       
        if (e.getKeyCode() == e.VK_ENTER) {
          synchronized(text){
            text = textArea.getText();
            System.out.println("Text entered.");
            text.notify();
          }
            }
    }

    public void keyReleased(KeyEvent e) {
        // Listen for the key pressed and check it against "Enter"
        // Then read out of our textarea control and print to screen4       
        if (e.getKeyCode() == e.VK_ENTER) {
            //do nothing
        }
    }

    public void keyTyped(KeyEvent e) {
        // Listen for the key pressed and check it against "Enter"
        // Then read out of our textarea control and print to screen4       
        if (e.getKeyCode() == e.VK_ENTER) {
            //do nothing
        }
    }


    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event dispatch thread.
     */
    public static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("TextDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Add contents to the window.
        frame.add(new TextDemo());

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event dispatch thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

}

当我运行代码时,它似乎工作,直到我按Enter键并且程序崩溃。错误代码(我只包括前5行,完整版本在这里:http://img.photobucket.com/albums/v242/ChaosGuide/illegalmonitorstateexception.png):

Exception in thread "AWT-EventQue-0" java.lang.IllegalMonitorStateException
    at java.lang.Object.notify(Native Method)
    at TextDemo.keyPressed(TextDemo.java:72)
    at java.awt.Component.processKeyEvent(Component.java:6463)
    at javax.swing.JComponent.processKeyEvent(JComponent.java:2829)
    at java.awt.Component.processEvent(Component.java:6282)

这是我第一次做任何甚至触及线程的事情,所以我真的不明白我做错了什么。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

两个线程都使用demo.text作为锁定,并在wait()上的同步块内调用此对象上的notify()demo.text进行通信,这是正确的。但是,在调用notify()之前,您正在为此变量重新分配新值。所以,实际上,你在一个你没有锁的对象上调用notify()

synchronized(text) { // this block is synchronized on the empty string object
    text = textArea.getText(); // you assign another string to text
    System.out.println("Text entered.");
    text.notify(); // you call notify on this other string object, but you don't own its lock, because you synchronized on the empty string
}

经验法则:当变量用作锁时,它应该是最终的,以避免这种错误。而且,使用空字符串作为锁是一个非常非常糟糕的主意。您最好创建一个专用对象来执行此操作:

private final Object lock = new Object();

但最好的办法是忘记wait()notify(),它们太低级了,并且从java.util.concurrent包中使用更高级别的抽象,如例如,信号量。

甚至更好:不是让主线程等待事件调度线程,而是最好启动后台线程,或者更确切地说使用SwingWorker来执行冗长的操作。