将对象传递到另一个线程 [英] passing objects to another thread

查看:119
本文介绍了将对象传递到另一个线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个GUI应用程序,并且在后台我想运行其他任务.我将粘贴一些代码,以防止粘贴由Swing生成的一堆代码,假设window.java可以按预期工作,我将省略一些部分.

i am creating a GUI application and in the background I want to run an additional task. I will paste some code, to prevent pasting a mess of code that was generated by Swing, I will leave some parts out, assume that the window.java is working as intended.

window.java:

window.java:

public class window {
frame = new JFrame();
JLabel lbl1 = new JLabel("Start Counter");
frame.add(lbl1);

Thread counter = new Thread(new counter());
    counter.start();
}

counter.java

counter.java

public class regCheck extends window implements Runnable
{

public void run()
{
    int i = 0;
    while (true)
    {
        window.lbl1.setText(i);
        try {Thread.sleep(1000);}
            catch (InterruptedException e) {e.printStackTrace();}
        i++;
    }
}
}

我希望本示例执行的操作是在窗口中创建标签,然后向上计数直到关闭程序. 此处的简单答案是说传递Jlabel",但实际上,我需要改变很多事情,而不仅是标签.

what I want this example to do is create a label within a window and count upwards until the program is closed. The easy answer here is to say "pass in the Jlabel" however in reality I have multiple things that I need to change not just a label.

"window.lbl1.setText(i);"行在这里不起作用,只是为了说明我想要实现的目标.

the line "window.lbl1.setText(i);" does not work here, it is just to illustrate what I want to achieve.

推荐答案

使用MVC模式.创建一个包含具有setValue()方法的计数器的模型,该方法会触发侦听器通知.您可以扩展java.util.Observable使其更容易实现.添加getValue()方法以检索新计数.使设置程序和获取程序同步以确保线程安全.

Use the MVC pattern. Create a model that has the counter with a setValue() method that fires a listener notification. You can extend java.util.Observable to make that easier to do. Add a getValue() method to retrieve the new count. Make the setter and getter synchronized for thread safety.

现在可以向线程传递模型的实例,并调用setValue()来更新其run()方法中的值.

Now your thread can be passed an instance of the model and call setValue() to update the value in its run() method.

最后,您的视图可以传递给模型的相同实例,并向其添加侦听器.为了简化操作,您的视图可以实现java.util.Observer.在视图中的侦听器update()回调中,调用模型的getValue(),然后将return用作setText()的参数.由于未从AWT事件调度程序线程调用侦听器更新,因此必须使用javax.swing.SwingUtilities.invokeLater()调用setText()才能满足Swing的线程安全要求.

Finally, your view can be passed the same instance of the model and add a listener to it. To make it easier your view can implement java.util.Observer. In the listener update() callback within the view, call the model's getValue() and use the return as the argument to setText(). Since the listener update is not being invoked from the AWT event dispatcher thread, you have to call setText() using javax.swing.SwingUtilities.invokeLater() in order to meet the thread safety requirements of Swing.

这篇关于将对象传递到另一个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆