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;
}
网友评论