【问题标题】:Thread return and synchronize [closed]线程返回和同步[关闭]
【发布时间】:2019-06-30 17:16:01
【问题描述】:


我正在制作纸牌游戏应用程序。我有 2 个线程:
线程 curr = 这里保存的是当前线程(JavaFx 线程)
Thread proHs = 这里是app的大脑,通过Interface运行方法
我想停止线程 proHs 停止一秒钟,直到我选择这两个按钮中的一个 ma​​m nemam
然后我必须返回 truefalse
我感谢任何建议或建议。 谢谢!

我试过无限循环

public boolean biddingStep(int gt) { //above this method is @Override, I can't post this with it
    System.out.println("  ");
    System.out.println("I HAVE OR NOT PART");
    try {
        proHs.wait();
    }
    catch (Exception e) {
        System.out.print(e);
    }
    panelLicitace.setVisible(true);
    mam.setVisible(true);
    nemam.setVisible(true);
    return false;//there would be the resolution of button "mam" or "nemam"
}


编辑#1
我想从你这里得到什么:

public boolean biddingStep(int gt) { //above this method is @Override, I can't post this with it
    System.out.println("  ");
    System.out.println("I HAVE OR NOT PART");
    panelLicitace.setVisible(true);
    mam.setVisible(true);
    nemam.setVisible(true);
    // HERE a code i want
    //1. stop proHS thread
    //2. loop program, wait for input from 2 buttons
    //3. return true or false
}

【问题讨论】:

  • 在共享Object 上的wait/notify,或在共享Condition 上的await/signal,或者使用类似BlockingQueue 的东西,并让JavaFX 线程将操作放入队列中其他线程将占用并执行。这些是线程通信的一些选项,但如果没有minimal reproducible example,我们将无法回答您的问题或查看您当前方法的问题(如果有);但是,proHs.wait() 看起来不正确。

标签: java multithreading javafx


【解决方案1】:

首先你需要了解wait()是Object类的方法,所以它就像一个特定的线程在等待一些与Object相关的动作。 所以在这里,如果 biddingStep(int gt) 在 proHs 线程下被调用并且您想停止 proHs 线程,基本上要等到选择特定按钮,然后您需要将等待放在某个对象上,一般来说,它应该是需要对其进行某些操作的对象。您需要在此处列出以下步骤:

  1. proHs 对象引用。
  2. 锁定 proHs 对象。
  3. 调用 proHs.wait()。

从第二个线程开始,您将执行以下操作: 1. 对 buttonClickListener 中的 proHs 对象加锁
第二个线程。) 2.调用proHs.notify()。

class InterfaceImpl {
    Thread proHs;
    boolean btnResponse;
    public boolean biddingStep(int gt) {
        System.out.println("  ");
        System.out.println("I HAVE OR NOT PART");
        panelLicitace.setVisible(true);
        mam.setVisible(true);
        nemam.setVisible(true);
        // HERE a code i want
        //1. stop proHS thread
        synchronized(proHs) {
            proHs.wait();
            //2. loop program, wait for input from 2 buttons
            //3. return true or false
            return btnResponse;
        }
    }   

    // This method should be called from another thread
    public boolean btnClickListener() { 
        btnResponse = true or false
        synchronized(proHs) {
            proHs.notify();
        }  
    }
}

这里 bidStep() 方法应该在 btnClickListener() 之前被调用,这样一旦线程等待,另一个线程就会通知它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-22
    • 1970-01-01
    • 2014-03-10
    • 1970-01-01
    • 1970-01-01
    • 2015-05-22
    相关资源
    最近更新 更多