java 将侦听器与线程一起使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12973678/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 11:01:04  来源:igfitidea点击:

Using Listener with Threads

javamultithreadingthread-safetylistener

提问by Yannick Wald

Say I have an Object Foo that wants to get informed by several running instances of a Thread using a listener interface. E.g.

假设我有一个对象 Foo,它希望使用侦听器接口通过线程的多个正在运行的实例获取通知。例如

The interface:

界面:

public interface ThreadListener {
   public void onNewData(String blabla);
}

The class Foo:

Foo 类:

public class Foo implements ThreadListener {
   public Foo() {
      FooThread th1 = new FooThread();
      FooThread th2 = new FooThread();
      ...

      th1.addListener(this);
      th2.addListener(this);
      ...

      th1.start();
      th2.start();
      ...
   }

   @Override
   public void onNewData(String blabla) {
     ...
   }
}

The Thread:

主题:

public FooThread extends Thread {
   private ThreadListener listener = null;

   public void addListener(ThreadListener listener) {
      this.listener = listener;
   }

   private void informListener() {
      if (listener != null) {
         listener.onNewData("Hello from " + this.getName());
      }
   }

   @Override
   public void run() {
     super.run();

     while(true) {
        informListener();
     }
   }
}

In the worst case onNewData(..) is invoked by several threads at the same time. What will happen with Foo? Is it going to crash or not?

在最坏的情况下,onNewData(..) 被多个线程同时调用。Foo会发生什么?它会崩溃吗?

回答by assylias

  • Your Fooclass has no state (fields), so unless it uses external shared resources (e.g. files...) it is thread safe
  • Starting thread from a constructor is generally a bad idea although in the case of a state-less object, I suppose it is fine
  • if onNewDatadoes not access shared data it will work as expected, if it does, the outcome will depend on how the method is implemented.
  • 您的Foo类没有状态(字段),因此除非它使用外部共享资源(例如文件...),否则它是线程安全的
  • 从构造函数启动线程通常是一个坏主意,尽管在无状态对象的情况下,我认为这很好
  • 如果onNewData不访问共享数据,它将按预期工作,如果访问,结果将取决于该方法的实现方式。