关于Thread对象的suspend,resume,stop方法(已过时)
2016-12-18 00:50
435 查看
一、作用
对于老式的磁带录音机,上面都会有暂停,继续,停止。Thread中suspend,resume,stop方法就类似。
suspend,使线程暂停,但是不会释放类似锁这样的资源。
resume,使线程恢复,如果之前没有使用suspend暂停线程,则不起作用。
stop,停止当前线程。不会保证释放当前线程占有的资源。
二、代码
代码中注释1的地方,线程会暂停输出,直到注释2处才恢复运行,到了注释3的地方,线程就被终止了。
suspend,resume,stop这样的方法都被标注为过期方法,因为其不会保证释放资源,容易产生死锁,所以不建议使用。
三、如何安全的暂停一个线程
使用一个volatile修饰的boolean类型的标志在循环的时候判断是否已经停止。
对于老式的磁带录音机,上面都会有暂停,继续,停止。Thread中suspend,resume,stop方法就类似。
suspend,使线程暂停,但是不会释放类似锁这样的资源。
resume,使线程恢复,如果之前没有使用suspend暂停线程,则不起作用。
stop,停止当前线程。不会保证释放当前线程占有的资源。
二、代码
public static void main(String[] args) { Thread thread = new Thread(new Runnable() { @Override public void run() { for (int i = 0; i <= 10000; i ++) { System.out.println(i); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } } }); thread.start(); try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } thread.suspend(); //注释1 try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } thread.resume(); //注释2 try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } thread.stop(); //注释3 System.out.println("main end.."); }
代码中注释1的地方,线程会暂停输出,直到注释2处才恢复运行,到了注释3的地方,线程就被终止了。
suspend,resume,stop这样的方法都被标注为过期方法,因为其不会保证释放资源,容易产生死锁,所以不建议使用。
三、如何安全的暂停一个线程
使用一个volatile修饰的boolean类型的标志在循环的时候判断是否已经停止。
public class Test { public static void main(String[] args) { Task task = new Task(); new Thread(task).start(); try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } task.stop(); System.out.println("main end..."); } static class Task implements Runnable { static volatile boolean stop = false; public void stop() { stop = true; } @Override public void run() { int i = 0; while (!stop) { System.out.println(i++); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } } } }
相关文章推荐
- 关于Thread对象的suspend,resume,stop方法
- [置顶] java thread的stop,suspend,resume等方法废弃的原因
- Why Are Thread.stop, Thread.suspend, Thread.resume and Runtime.runFinalizersOnExit Deprecated ?
- 自己实现线程的start、suspend、resume、stop方法
- Java中的线程Thread方法之---suspend()和resume()
- Java中的线程Thread方法之---suspend()和resume()
- Java中的线程Thread方法之---suspend()和resume()
- Java中的线程Thread方法之---suspend()和resume()
- 我爱学Java之Thread中stop(),suspend(),resume()为什么不安全
- Thread 的stop方法过时Thread already start解决方法
- java 线程Thread方法之suspend()和resume()
- Thread的suspend和stop方法的一些问题
- Why Are Thread.stop, Thread.suspend, Thread.resume and Runtime.runFinalizersOnExit Deprecated ?
- 为什么java线程不推荐调用stop,suspend,resume方法
- 为何java里的Thread类的方法suspend()和resume()不推荐使用?
- Thread的suspend和stop方法的一些问题
- Java中的线程Thread方法之suspend()和resume()
- Thread中的stop方法过时
- java中resume() stop()方法已经过时用什么方法代替呢
- Java中的线程Thread方法之---suspend()和resume()