打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
基础篇:让线程停止运行的几种方式

这篇文章我们来讨论一下终止线程运行的方法;

中断线程的方法:

  1. public static void stopThread() throws InterruptedException{
  2. Thread t = new Thread(new Runnable() {
  3. @Override
  4. public void run() {
  5. while(!Thread.currentThread().isInterrupted()){
  6. System.out.print("run,");
  7. }
  8. }
  9. });
  10. t.start();
  11. //1毫秒后发送中断命令
  12. TimeUnit.MILLISECONDS.sleep(1);
  13. t.interrupt();
  14. System.out.println("\r\n中断完毕,主线程运行完毕!");
  15. }

输出**********************************************************************

run,run,run,run,run,run,run,run,run,run,run,
中断完毕,主线程运行完毕!

***************************************************************************


我们在run中 通过调用 当前线程的 isInterrupted()方法来判断当前线程是否已被中断,如果没有则一直循环运行;

而在主线程中,我们等待1毫秒后对 t 这个线程发送中断命令,在输出结果中可以看到,t线程已成功停止运行;



停止线程池中全部线程的方法:

  1. class StopThread implements Runnable{
  2. @Override
  3. public void run() {
  4. try {
  5. System.out.println("run...");
  6. TimeUnit.MILLISECONDS.sleep(2000);
  7. System.out.println("run...over...");
  8. } catch (InterruptedException e) {
  9. e.printStackTrace();
  10. }
  11. }
  12. }
  13. //终止线程池内全部线程
  14. public static void stopAllThread() throws InterruptedException{
  15. ExecutorService exec = Executors.newCachedThreadPool();
  16. for (int i = 0; i < 5; i++) {
  17. exec.execute(new StopThread());
  18. }
  19. //这将立即中断该线程池内所有运行或者阻塞的线程
  20. exec.shutdownNow();
  21. System.out.println("stopBlocking()...over...");
  22. }
输出********************************************************************************

run...
run...
stopBlocking()...over...
run...
run...
run...

***********************************************************************************
可以看到,所有线程都只打印出了run...而没有打印run...over...   这代表它们已经被成功停止了!

需要注意的是:如果我们调用exec.shutdown(),这会让已经处于运行中的任务继续运行下去而不会被成功停止...



停止线程池中单个线程的方法:

  1. //终止单个线程
  2. public static void stopSingleThread(){
  3. ExecutorService exec = Executors.newCachedThreadPool();
  4. List<Future> fs = new ArrayList<Future>();
  5. for (int i = 0; i < 5; i++) {
  6. Future f = exec.submit(new StopThread());
  7. fs.add(f);
  8. }
  9. //立即停止第一个线程!如果参数为false,则等待任务执行完毕;
  10. fs.get(0).cancel(true);
  11. }

输出*****************************************************************************

run...
run...
run...
run...
run...

run...over...
run...over...
run...over...
run...over...

**********************************************************************************

这个输出结果是没问题的,因为有一个线程已经被停止了,所以只有四行run...over...打印;

我们通过改为调用exec的submit方法而不是execute方法 从而拿到一个Future对象,每个Future对应于一个运行着的线程,当我们调用Future的cancel(true)方法时,对应的线程将终止运行;


论证:IO阻塞和等待synchronized锁造成的阻塞中的线程无法被中断!

  1. Object tempObj = new Object();
  2. private static void holdLock(){
  3. //开启一个线程持有tempObj的锁
  4. new Thread(new Runnable() {
  5. public void run() {
  6. synchronized (tempObj) {
  7. try {
  8. TimeUnit.MILLISECONDS.sleep(500);
  9. } catch (InterruptedException e) {}
  10. }
  11. }
  12. }).start();
  13. }
  14. //证明IO阻塞和等待锁阻塞中的线程无法被中断!
  15. public static void stopByIoAndLockThread() throws IOException{
  16. holdLock();
  17. final InputStream in = System.in;
  18. ExecutorService exec = Executors.newCachedThreadPool();
  19. exec.execute(new Runnable() {
  20. public void run() {
  21. System.out.println("io Blocking...");
  22. try {
  23. //等待IO读写
  24. in.read();
  25. System.out.println("io Blocking...over...");
  26. } catch (IOException e) {
  27. e.printStackTrace();
  28. }
  29. }
  30. });
  31. exec.execute(new Runnable() {
  32. public void run() {
  33. System.out.println("Lock Blocking...");
  34. //等待对象锁,已在holdLock()中被持有
  35. synchronized (tempObj) {
  36. System.out.println("Lock Blocking...over...");
  37. }
  38. }
  39. });
  40. //中断这两个线程,我们可以看输出,这代码压根没效果
  41. exec.shutdownNow();
  42. }




你可以复制上面的代码去运行一下,事实证明处理这两种阻塞中的线程时无法停止的;

由此引入了一个问题,如果某个线程获取了对象锁,但它运行之中出现了问题导致锁一直不被释放,我们又希望能终止该线程的运行好让其它线程能拿到锁从而做些操作,此时该怎么办呢?答案是不采用synchronized进行同步操作,而采用ReentrantLock;

代码如下:

  1. //synchronized造成的阻塞让线程无法停止,但java的Lock对象造成的阻塞是可以让线程停止的!
  2. public static void allowStopByLock(){
  3. System.out.println("allowStopByLock()...");
  4. final ReentrantLock lock = new ReentrantLock();
  5. lock.lock();//永久的持有锁
  6. Thread thread = new Thread(new Runnable() {
  7. public void run() {
  8. try {
  9. System.out.println("准备获取lock锁...");
  10. //如果当前线程未中断,则获取锁
  11. lock.lockInterruptibly();
  12. System.out.println("已获取到锁,执行完毕!");
  13. } catch (InterruptedException e) {
  14. e.printStackTrace();
  15. }
  16. }
  17. });
  18. thread.start();
  19. //interrupt方法调用完后可以看到线程已经停止了
  20. thread.interrupt();
  21. System.out.println("allowStopByLock()...over...");
  22. }


Ok,关于停止线程运行的相关方法就讲到这里;后面我们开始来讲点真正有用的东西!

https://blog.csdn.net/cy_alone/article/details/69855700


本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Java实现定时任务的三种方法
多线程/JAVA多线程 - 魔乐培训 高端JAVA培训 魔乐科技JAVA培训
趣谈并发(1):全面认识 Thread
多线程详解
Java多线程之CyclicBarrier
Java 线程基础
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服