【问题标题】:java Singleton Infinitely Running Thread : Restartjava Singleton无限运行线程:重新启动
【发布时间】:2018-01-15 13:21:01
【问题描述】:

在网络服务器中需要不断地轮询才能执行某些任务。实现了 Singleton 类,因此没有开发人员可以意外创建多个线程。线程在 Web 应用程序启动 SingletonThread.getInstance().start() 时启动。我的问题是运行状况检查,在运行状况检查中,我监视线程是否处于活动状态,如果由于某种原因线程变得不活动,我无法创建新线程,因为实例是单例的,并且当在同一线程实例上调用两次 start 方法时,它会抛出 IllegalThreadStateException。想知道这是否可以解决。

在单例类中运行线程。

代码

Class SingletonThread Extends Thread {

      private static SingletonThread objSingletonThread;

      public static SingletonThread getInstance() {

        if (objSingletonThread== null) {
          synchronized(SingletonThread.class) {
            if (objSingletonThread== null) 
              objSingletonThread= new SingletonThread ();
          }
        }
        return objSingletonThread;
      }

    private SingletonThread () {
    }

    @Override
    public void run() {
      while(true) {
       // some polling code with all exception catch
      }
    }
}

健康检查类方法

   private boolean isPollingThreadActive() {
       return SingletonThread.getInstance().isAlive();
    }

    public void healthCheck() {
        if(!isPollingThreadActive()) {
           // start thread again
           // cannot use singleton instance because it throws
           // IllegalStateException
        }
    }

【问题讨论】:

  • 为什么你的班级还是单身?
  • start()线程一旦创建,或者在构造函数中
  • 我不明白你的问题。你能再详细一点吗?此外,你不能“重启”一个线程,它可能会抛出一个 IllegalThreadStateException 你尝试这样做。
  • 您的代码有效吗?很奇怪:)
  • 什么是资源?

标签: java multithreading


【解决方案1】:

你可以调用一个更适合你的类。

public class Singleton {

    private static Singleton singleton;

    public static synchronized Singleton getInstance(){
        if(singleton == null)
            return singleton = new Singleton();

        return singleton;
    }

    public void invoke(){
        //TODO
    }

}


public class MyThread extends  Thread {

    @Override
    public void run() {
        Singleton.getInstance().invoke();
    }
}

【讨论】:

  • 我创建线程类单例的意图是任何开发人员都不应意外创建线程类的另一个实例。这样不会有超过一个线程轮询任务。所以不能使用上面的解决方案,因为我们可以创建多个 MyThread 类的实例[并且可能是多个线程]。
猜你喜欢
  • 2018-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-25
  • 1970-01-01
相关资源
最近更新 更多