2012-06-18 36 views
0

在我的Android应用程序中,我有一个延伸Thread的类,它在建立Internet连接(3G/WIFI)时运行。正确的方法来结束一个类的实例?

当应用程序被加载,如果建立了互联网连接,我实例化类是这样的:

MyThread thread = new MyThread(); // (it calls its own start() method) 

在线程中,如果连接丢失,我要摧毁Thread。我被告知不要运行finalize(),我将如何销毁它以便thread == null为真?


编辑:我是问的原因是,后来,我想在连接的情况下返回到重新启动线程,并看到一个检查,如果(thread == null)本来是很容易。我可以使用一个标志来指示线程需要重新启动,或者检查它是否被中断。感谢迄今为止有用的评论。

+2

从你的线程就返回,当连接丢失垃圾收集器会照顾它 – GETah

+1

,调用'中断()'你的主题。 – Sajmon

+0

创建一个标志并在线程运行时将其设置为true。当你想停止时简单地将其设置为false。这样你可以确定线程不会继续在后台运行。把它留给垃圾收集器。 – Orlymee

回答

1

通常,您不会继承Thread。您创建一个Runnable,并将其传递给Thread对象,或者更好的是ExecutorService

但是,在线程完成后,您不必担心清理问题,它将由垃圾回收器自动处理。如果你想让你自己的本地引用为null,那么你自己就可以将它清空,或者更好,不要挂在它上面。

new Thread(new Runnable() { 
    public void run() { 
     // put your stuff here 
    } 
}).start(); 
1

尝试此,

  1. thread of execution will live until it has finished executing its run() method,然后 它或者移动到dead stat E或在thread pool

  2. 它总是更好地控制run()方法使用boolean variable

    如:

    boolean isRunning = true; 
    
        new Thread(new Runnable() 
    
         { 
    
        public void run() 
    
         { 
    
        while(isRunning) 
    
         { 
    
          // Keep doing your work here.... 
    
           if (!isRunning){ 
    
             break; 
            } 
    
    
           } 
    
        } 
    

    }).start();

+0

请注意,布尔标志需要同步才能确保两个线程中的可见性。 – wolfcastle

+0

谢谢你的帮助。 – StackOverflowed

相关问题