美文网首页
在Activity、fragment使用new Thread导致

在Activity、fragment使用new Thread导致

作者: Maaaaxi | 来源:发表于2019-08-02 16:04 被阅读0次
    new Thread(new Runnable() { 
        @Override public void run() { 
      } 
    }).start();
    

    以上方法会浪费线程资源,极有可能导致内存泄漏,解决方法有两种:

    1.把该线程类声明为私有的静态内部类:

     public class MainActivity extends Activity {
    
          @Override
          protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            exampleTwo();
          }
    
          private void exampleTwo() {
            new MyThread().start();
          }
    
          private static class MyThread extends Thread {
            @Override
            public void run() {
              while (true) {
                SystemClock.sleep(1000);
              }
            }
          }
        }
    
    public class MainActivity extends Activity {
          private MyThread mThread;
    
          @Override
          protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            exampleThree();
          }
    
          private void exampleThree() {
            mThread = new MyThread();
            mThread.start();
          }
    
          /**
           * 私有的静态内部类不会持有其外部类的引用,使得 Activity 实例不会在配置改变时发生内
           * 存泄漏
           */
          private static class MyThread extends Thread {
            private boolean mRunning = false;
    
            @Override
            public void run() {
              mRunning = true;
              while (mRunning) {
                SystemClock.sleep(1000);
              }
            }
    
            public void close() {
              mRunning = false;
            }
          }
    
          @Override
          protected void onDestroy() {
            super.onDestroy();
            mThread.close();
          }
    }
    

    相关文章

      网友评论

          本文标题:在Activity、fragment使用new Thread导致

          本文链接:https://www.haomeiwen.com/subject/gtgldctx.html