停止基于服务的线程

停止基于服务的线程

  应用程序通常会创建拥有服务的线程, 比如线程池. 这些服务的存在时间通常要比创建他们的方法存在的时间更长, 如果应用程序优雅的退出了,这些服务的线程也需要结束.因为没有退出线程惯用的优先方法, 他们需要自行结束.

  明智的封装实践指出,你不应该操控某个线程一一中断它,改变他的优先级,等等... 除非是这个.线程的拥有者, 线程API没有关于线程所属权正规的概念. 线程通过一个Thread对象表示,和其他对象一样可以被自由的共享. 但是, 认为线程有一个拥有者是有道理的. 这个拥有者就是创建这个线程的类. 所有线程池拥有它的工作线程, 如果需要中断这些线程. 那么应该由线程池来负责

  例如: ExecutorService 提供的 shutdown 和 shutdownNow 方法.

  对于线程持有的服务, 只要服务的存在时间大于创建线程的方法存在时间,那么就应该提供生命周期方法(lifecycle method)

实例: 日志服务

public class LogService {
    private final BlockingQueue<String> queue;
    private final LoggerThread loggerThread;
    private final PrintWriter writer;
    private boolean isShutdown;
    private int reservations;

    public LogService(Writer writer) {
        this.queue = new LinkedBlockingQueue<String>();
        this.loggerThread = new LoggerThread();
        this.writer = new PrintWriter(writer);
    }

    public void start() {
        loggerThread.start();
    }

    public void stop() {
        synchronized (this) {
            isShutdown = true;
        }
        loggerThread.interrupt();
    }

    public void log(String msg) throws InterruptedException {
        synchronized (this) {
            if (isShutdown)
                throw new IllegalStateException(/* ... */);
            ++reservations;
        }
        queue.put(msg);
    }

    private class LoggerThread extends Thread {
        public void run() {
            try {
                while (true) {
                    try {
                        synchronized (LogService.this) {
                            if (isShutdown && reservations == 0)
                                break;
                        }
                        String msg = queue.take();
                        synchronized (LogService.this) {
                            --reservations;
                        }
                        writer.println(msg);
                    } catch (InterruptedException e) { /* retry */
                    }
                }
            } finally {
                writer.close();
            }
        }
    }
}

或者使用 ExecutorService

public class LogService2 {

    private final ExecutorService executorService = Executors
            .newSingleThreadExecutor();
    private final PrintWriter writer;

    public LogService2(PrintWriter writer) {
        super();
        this.writer = writer;
    }

    public void start() {
    }

    public void close() {
        try {

            this.executorService.shutdown();
            this.executorService.awaitTermination(TIME_OUT, UNIT);
        } finally {
            if (writer != null)
                writer.close();
        }
    }

    public void log(String str) {
        this.executorService.execute(new Writer(str));
    }

}

实例: 致命药丸

public class IndexingService {
    private static final int CAPACITY = 1000;
    private static final File POISON = new File("");
    private final IndexerThread consumer = new IndexerThread();
    private final CrawlerThread producer = new CrawlerThread();
    private final BlockingQueue<File> queue;
    private final FileFilter fileFilter;
    private final File root;

    public IndexingService(File root, final FileFilter fileFilter) {
        this.root = root;
        this.queue = new LinkedBlockingQueue<File>(CAPACITY);
        this.fileFilter = new FileFilter() {
            public boolean accept(File f) {
                return f.isDirectory() || fileFilter.accept(f);
            }
        };
    }

    private boolean alreadyIndexed(File f) {
        return false;
    }

    class CrawlerThread extends Thread {
        public void run() {
            try {
                crawl(root);
            } catch (InterruptedException e) { /* fall through */
            } finally {
                while (true) {
                    try {
                        queue.put(POISON);
                        break;
                    } catch (InterruptedException e1) { /* retry */
                    }
                }
            }
        }

        private void crawl(File root) throws InterruptedException {
            File[] entries = root.listFiles(fileFilter);
            if (entries != null) {
                for (File entry : entries) {
                    if (entry.isDirectory())
                        crawl(entry);
                    else if (!alreadyIndexed(entry))
                        queue.put(entry);
                }
            }
        }
    }

    class IndexerThread extends Thread {
        public void run() {
            try {
                while (true) {
                    File file = queue.take();
                    if (file == POISON)
                        break;
                    else
                        indexFile(file);
                }
            } catch (InterruptedException consumed) {
            }
        }

        public void indexFile(File file) {
            /* ... */
        };
    }

    public void start() {
        producer.start();
        consumer.start();
    }

    public void stop() {
        producer.interrupt();
    }

    public void awaitTermination() throws InterruptedException {
        consumer.join();
    }

    public static void main(String[] args) {
        IndexingService is =new IndexingService(new File("e://"), new FileFilter() {

            public boolean accept(File pathname) {
                System.out.println(pathname);
                return true;
            }
        });
        is.start();
        is.stop();
        try {
            is.awaitTermination();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("the end ");
    }
}

  致命药丸只有在生产线程与消费线程已知的情况下才能使用. IndexingService中的解决方案也可以被扩展到多生产者, 只要让每一个生产线程都往队列里放入一个药丸, 并且消费线程收到第 N(生产者的数量)个药丸时停止.

实例: 只执行一次的服务

时间: 2024-07-28 22:53:25

停止基于服务的线程的相关文章

并发编程—— 任务取消 之 停止基于线程的服务

Java并发编程实践 目录 并发编程—— ConcurrentHashMap 并发编程—— 阻塞队列和生产者-消费者模式 并发编程—— 闭锁CountDownLatch 与 栅栏CyclicBarrier 并发编程—— Callable和Future 并发编程—— CompletionService : Executor 和 BlockingQueue 并发编程—— 任务取消 并发编程—— 任务取消 之 中断 并发编程—— 任务取消 之 停止基于线程的服务 概述 第1 部分 问题描述 第2 部分

不停止 MySQL 服务增加从库的两种方式

不停止 MySQL 服务增加从库的两种方式 提交 我的评论 加载中 已评论 不停止 MySQL 服务增加从库的两种方式 2015-07-12 数据库开发 数据库开发 数据库开发 微信号 DBDevs 功能介绍 分享数据库相关技术文章.教程和工具,另外还包括数据库相关的工作.偶尔也谈谈程序员人生 :) (点击上方蓝字,快速关注我们) 作者:李振良 网址:http://lizhenliang.blog.51cto.com/7876557/1669829 现在生产环境MySQL数据库是一主一从,由于业

不停止MySQL服务增加从库的两种方式【转载】

现在生产环境MySQL数据库是一主一从,由于业务量访问不断增大,故再增加一台从库.前提是不能影响线上业务使用,也就是说不能重启MySQL服务,为了避免出现其他情况,选择在网站访问量低峰期时间段操作. 一般在线增加从库有两种方式,一种是通过mysqldump备份主库,恢复到从库,mysqldump是逻辑备份,数据量大时,备份速度会很慢,锁表的时间也会很长.另一种是通过xtrabackup工具备份主库,恢复到从库,xtrabackup是物理备份,备份速度快,不锁表.为什么不锁表?因为自身会监控主库日

在CentOS 7中启动/停止/重启服务

RHEL/CentOS 7.0中一个最主要的改变,就是切换到了systemd.它用于替代红帽企业版Linux前任版本中的SysV和Upstart,对系统和服务进行管理.systemd兼容SysV和Linux标准组的启动脚本. Systemd是一个Linux操作系统下的系统和服务管理器.它被设计成向后兼容SysV启动脚本,并提供了大量的特性,如开机时平行启动系统服务,按需启动守护进程,支持系统状态快照,或者基于依赖的服务控制逻辑. 先前的使用SysV初始化或Upstart的红帽企业版Linux版本

Linux Systemd——在RHEL/CentOS 7中启动/停止/重启服务

RHEL/CentOS 7.0中一个最主要的改变,就是切换到了systemd.它用于替代红帽企业版Linux前任版本中的SysV和Upstart,对系统和服务进行管理.systemd兼容SysV和Linux标准组的启动脚本. Systemd是一个Linux操作系统下的系统和服务管理器.它被设计成向后兼容SysV启动脚本,并提供了大量的特性,如开机时平行启动系统服务,按需启动守护进程,支持系统状态快照,或者基于依赖的服务控制逻辑. 先前的使用SysV初始化或Upstart的红帽企业版Linux版本

Android系统Surface机制的SurfaceFlinger服务的线程模型分析

文章转载至CSDN社区罗升阳的安卓之旅,原文地址:http://blog.csdn.net/luoshengyang/article/details/8062945 在前面两篇文章中,我们分析了SurfaceFlinger服务的启动过程以及SurfaceFlinger服务初始化硬件帧缓冲区的过程.从这两个过程可以知道,SurfaceFlinger服务在启动的过程中,一共涉及到了三种类型的线程,它们分别是Binder线程.UI渲染线程和控制台事件监控线程.在本文中,我们就将详细分SurfaceFl

Appium+Python app自动化测试之脚本启动和停止Appium服务

研究了一段时间的Appium android app的自动化测试,工作中需要连接多台手机终端同时执行测试用例,我实现的方式是获取用例中需要执行用例的设备id个数以及实际连接到的设备数(通过adb devices获取),然后启动相应数量的Appium 服务,以便每个设备执行时并发进行并且互不影响.当然也可以通过selenium grid来实现,只是目前还在学习研究中,还是先把目前启动多个appium服务实现的方式记录下来. 一.Windows下启动单个appium服务 需要启动多个appium服务

如何停止AAD服务

Connect-MsolService (Get-MSOLCompanyInformation).DirectorySynchronizationEnabled 用这个命令查看是enable还是Disable的 Set-MsolDirSyncEnabled -EnableDirSync $false 执行断开! 停止aad服务需要72小时 或者界面上运行

启动和启动和停止MySQL服务停止MySQL服务

1.  启动MySQL服务 启动MySQL服务的命令为: /etc/init.d/mysqld start 命令执行后如图7-5所示,表示启动MySQL服务成功.   (点击查看大图)图7-5  启动MySQL服务 也可以用/etc/init.d/mysqld的简化命令启动MySQL服务: service mysqld start 命令执行结果如图7-6所示.   (点击查看大图)图7-6  service命令启动MySQL服务 2.  停止MySQL服务 停止MySQL服务的命令为: W/et