有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (3) 个答案

  1. # 1 楼答案

    为了做到这一点,您需要将^{}任务ExecutorService,而不是调用execute()。执行此操作时,将返回一个Future,可用于操作计划任务。特别是,您可以在关联的Future上调用^{}来中断当前正在执行的任务(如果任务尚未开始运行,则完全跳过执行)

    顺便说一下,^{}返回的对象实际上是一个ExecutorService

  2. # 2 楼答案

    一种合适的方法是为executorservice定制/注入ThreadFactory,在线程工厂中,创建线程的句柄,然后安排一些任务来中断感兴趣的线程

    ThreadFactory中被覆盖的方法“newThread”的演示代码部分:

    ThreadFactory customThreadfactory new ThreadFactory() {
    
                public Thread newThread(Runnable runnable) {
                    final Thread thread = new Thread(runnable);
                    if (namePrefix != null) {
                        thread.setName(namePrefix + "-" + count.getAndIncrement());
                    }
                    if (daemon != null) {
                        thread.setDaemon(daemon);
                    }
                    if (priority != null) {
                        thread.setPriority(priority);
                    }
    
                    scheduledExecutorService.schedule(new Callable<String>() {
                        public String call() throws Exception {
                            System.out.println("Executed!");
                            thread.interrupt();
                            return "Called!";
    
                        }
                    },
                    5,
                    TimeUnit.SECONDS);
    
                    return thread;
                }
            }
    

    然后,您可以使用以下内容构建executorservice实例:

    ExecutorService executorService = Executors.newFixedThreadPool(3,
            customThreadfactory);
    

    然后在5秒后,一个中断信号将发送到executorservice中的线程

  3. # 3 楼答案

    中断执行器的内部管理线程的另一种方法是在ExecutorService上调用shutdownNow(..)方法。但是,请注意,与@erickson的解决方案相反,这将导致整个ThreadPoolExecutor变得不适合进一步使用

    我发现这种方法在不再需要ExecutorService的情况下特别有用,并且不需要对Future实例进行监视(应用程序的exit(..)方法就是一个很好的例子)

    来自Java文档的相关信息:

    Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.

    There are no guarantees beyond best-effort attempts to stop processing actively executing tasks. For example, typical implementations will cancel via Thread.interrupt, so any task that fails to respond to interrupts may never terminate.