/**
* Created by JuTao on 2017/2/4.
* 如何中止一个线程
*/
public class ThreadDone {
public static void main(String[] args) throws InterruptedException {
MyRunnable myRunnable=new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
Thread.sleep(1000);
//仅仅利用flag并不能使线程立刻中止,当run方法中有耗时操作时会等待执行完成才结束
myRunnable.flag=false;
thread.interrupt();
}
private static class MyRunnable implements Runnable {
//立刻同步到子线程中
private volatile boolean flag = true;
@Override public void run() {
while (flag&&!Thread.interrupted()) {
System.out.println("running");
try {
Thread.sleep(8000);
} catch (InterruptedException e) {
//e.printStackTrace();
//thread.interrupt()执行后会立刻进入catch
return;
}
}
}
}
}
相关文章
- 04-22android – 如何从另一个活动或另一个线程触摸EditTextPrefences
- 04-22一个神奇的bug:OOM?优雅终止线程?系统内存占用较高?
- 04-22android一个上传图片的样例,包含怎样终止上传过程,假设在上传的时候更新进度条(一)
- 04-22无废话Android之smartimageview使用、android多线程下载、显式意图激活另外一个activity,检查网络是否可用定位到网络的位置、隐式意图激活另外一个activity、隐式意图的配置,自定义隐式意图、在不同activity之间数据传递(5)
- 04-2210.4 android输入系统_框架、编写一个万能模拟输入驱动程序、reader/dispatcher线程启动过程源码分析
- 04-22android一个上传图片的例子,包括如何终止上传过程,如果在上传的时候更新进度条(二)
- 04-22android一个上传图片的例子,包括如何终止上传过程,如果在上传的时候更新进度条(一)
- 04-22记录关于Android多线程的一个坑
- 04-22android:Faild to install,你的主机中的软件终止了一个连接错误解决
- 04-22Android 性能优化(16)线程优化:Creating a Manager for Multiple Threads 如何创建一个线程池管理类