美文网首页
Android项目YQSM小知识整理

Android项目YQSM小知识整理

作者: 大浪捉鱼 | 来源:发表于2022-11-28 12:05 被阅读0次

    1、如何停止一个线程
    不要用Thread.stop(),而要像下面这样停止线程,更多信息请看官方文档 https://docs.oracle.com/javase/8/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html

    
      private volatile Thread mThread;
    
     /**
         * 启动线程更新当前日期和时间
         */
        private void startThread() {
            mThread = new Thread(() -> {
                Thread thisThread = Thread.currentThread();
                while (mThread == thisThread ) {
                    try {
                        Thread.sleep(1000);
                        Message mesasge = new Message();
                        mesasge.what = 100;
                        mHandler.sendMessage(mesasge);
    
                    } catch (InterruptedException e ) {
                        e.printStackTrace();
                    }
    
                }
    
                Log.i(TAG, "Thread was stop");
    
            });
            mThread.start();
        }
    
        private void updateDatetime() {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
            datetimeTv.setText(sdf.format(new Date(System.currentTimeMillis())));
        }
    
        private void stopThread() {
            mThread = null;
        }
    

    2、Java基础:volatile详解

    相关文章

      网友评论

          本文标题:Android项目YQSM小知识整理

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