线程通信:如何发出点击密钥的信号? java.lang.IllegalMonitorStateException

时间:2017-04-06 13:24:20

标签: java multithreading javafx conditional-statements

我有一个带TextField的简单JavaFX阶段。我想要做的是:当用户在TextField中插入字母时,我想打印"现在" (只是看它是否有效)。我正在使用一个Thread,因为后来我想扫描一个dictonary来查看,如果用户输入的字母是字典中单词的一部分。

但我得到:java.lang.IllegalMonitorStateException

有什么想法吗?我似乎并不了解Condition.await和Multithreading的整个概念。

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class DictionaryThreading extends Application {


private static Lock lock = new ReentrantLock();
public static Condition condition = lock.newCondition();

public static void main(String[] args) {
    launch();
}

private static class ScanWords implements Runnable{

    @Override
    public void run() {
        lock.lock();
        try{    
            while(true){
                this.wait();
                System.out.println("clicked");
            }
        } catch (Exception e){
            e.printStackTrace();
        } finally{
            lock.unlock();
        }   
    }

}

@Override
public void start(Stage primaryStage) throws Exception {
    StackPane pane = new StackPane();

    new ScanWords().run();
    TextField tf = new TextField("Please enter a word");
    tf.setOnKeyPressed(e -> {});
    pane.getChildren().add(tf);

    Scene scene = new Scene(pane);
    primaryStage.setScene(scene);
    primaryStage.show();

}

}

3 个答案:

答案 0 :(得分:2)

除了等待用户事件之外,不需要创建只执行任何操作的线程。 JavaFX框架已经为您提供了这个功能(它是任何 UI工具包的基本功能之一)。要在文本字段中响应文本中的更改,您需要做的就是使用文本字段的文本属性注册更改侦听器:

public void start(Stage primaryStage) throws Exception {
    StackPane pane = new StackPane();

    TextField tf = new TextField("Please enter a word");
    tf.textProperty().addListener((obs, oldText, newText) -> {
        System.out.println("text changed");
    });
    pane.getChildren().add(tf);

    Scene scene = new Scene(pane);
    primaryStage.setScene(scene);
    primaryStage.show();

}

如果您为响应文本更改而需要做的事情需要花费很长时间,那么您应该在文本字段的侦听器中的后台线程中启动该进程。如果您正在搜索大型内容,您可能希望取消任何现有搜索,这样您就不会同时运行大量搜索。 JavaFX Service class提供了您需要的功能:

public class SearchService extends Service<List<String>> {

    // modify and access only on FX Application Thread:
    private String searchString ;

    @Override
    protected Task<List<String>> createTask() {
        final String s = searchString ;
        return new Task<List<String>>() {
            @Override
            protected List<String> call() throws Exception {
                List<String> matches = new ArrayList<>();
                // do search for strings matching s
                // be sure to check isCancelled() regularly
                return matches ;
            }
        };
    }

    public String getSearchString() {
        checkThread();
        return searchString ;
    }

    public void setSearchString(String searchString) {
        checkThread();
        this.searchString = searchString ;
    }

    private void checkThread() {
        if (! Platform.isFxApplicationThread()) {
            throw new IllegalStateException("Not on FX Application Thread");
        }
    }
}

然后你可以做

public void start(Stage primaryStage) throws Exception {
    StackPane pane = new StackPane();

    SearchService searchService = new SearchService();

    searchService.setOnSucceeded(e -> {
        List<String> matches = searchService.getValue();
        // do whatever you need with search results...
        // this is called on FX application thread
    });

    TextField tf = new TextField("Please enter a word");
    tf.textProperty().addListener((obs, oldText, newText) -> {
        searchService.cancel();
        searchService.setSearchText(newText);
        searchService.restart();
    });
    pane.getChildren().add(tf);

    Scene scene = new Scene(pane);
    primaryStage.setScene(scene);
    primaryStage.show();

}

答案 1 :(得分:0)

我不使用JavaFX,但我认为您需要使用EventListener。尝试使用TextListenerInputMethodListener。例如:

StackPane pane = new StackPane();

TextField tf = new TextField("Please enter a word");

tf.addTextListener(e -> System.out.println("Pushed"));

pane.getChildren().add(tf);

Scene scene = new Scene(pane);
primaryStage.setScene(scene);
primaryStage.show();

答案 2 :(得分:-1)

wait方法应在synchronized块中执行:

    try{    
        while(true){
            synchronized(this){
                this.wait();
                System.out.println("clicked");
            }
        }
    } catch (Exception e){
        e.printStackTrace();
    } finally{
        lock.unlock();
    }