-
java中如何强制停止线程?3
网上很多方法,什么设置标志,当前线程自己退出,不通过监控线程来停止。这样如果当前线程本身就是需要处理很多任务,但处理这些任务需要有一个时间限制,超过这个时间限制我就必需要强制停止他怎么办呢?
用stop也是不可取的办法。有没有其它的办法呢?
问题补充:xiaoZ5919 写道我看tomcat停
止线程有使用抛异常的方式还有一位仁兄提到中断interpreted
我的问题场景是:void service() { methodA(); methodB(); methodC(); methodD(); methodE(); }
现在service可能执行的时间会大于1分钟,但我想只要service执行时间超过一分钟(这个可以通过检测线程状态来判断是否到了这个时间),然后就强制该service所在的线程停止。不管运行到哪个位置。必需停止。类型于linux下的kill一样强制杀掉进程。
设置标志位如果我的service根本不在循环中,我也不知道该在哪个位置去加flag的判断啊。不可能每个地方都做下flag判断吧?这样的结果是不确定的。
问题补充:OpenMind 写道你的service是否操作某些资源,比如IO、数据库连接等等,你可以在外部强制关闭资源,这样处理线程会抛出出异常而结束。这也算是一个方法吧
这种都不是一种绝对的解决办法,如果我的service当前不是在操作IO或者一些外部资源呢,而且我也不知道当前在做什么操作。因为我要的是任何我想它停的时候就得停。
问题补充:yx200404 写道import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class A { //自己设置大小,这里设置的是一个单工作线程 final ExecutorService exec = Executors.newSingleThreadExecutor(); public void send() { TaskThread taskThread = new TaskThread(); Future<Object> taskFuture = exec.submit(taskThread); try { //此处看任务线程是否返回值,如果不返回,那么在1分钟后任务线程会被强行终止 taskFuture.get(1, TimeUnit.MINUTES); } catch (InterruptedException ex) { // } catch (ExecutionException ex) { // } catch (TimeoutException ex) { // } finally { } } class TaskThread implements Callable<Object> { public Object call() throws Exception { methodA(); methodB(); methodC(); methodD(); methodE(); return false; } } }
哥们些,什么年代了...还在自己搞"终止"处理~public class StopThreadTest { //自己设置大小,这里设置的是一个单工作线程 private static boolean isTO = false; final ExecutorService exec = Executors.newSingleThreadExecutor(); public void send() { TaskThread taskThread = new TaskThread(); Future<Object> taskFuture = exec.submit(taskThread); try { //此处看任务线程是否返回值,如果不返回,那么在1分钟后任务线程会被强行终止 System.err.println("taskResult:" + taskFuture.get(5, TimeUnit.SECONDS)); System.err.println("taskStat:" + taskFuture.isCancelled()); } catch (InterruptedException ex) { ex.printStackTrace(); } catch (ExecutionException ex) { ex.printStackTrace(); } catch (TimeoutException ex) { ex.printStackTrace(); isTO = true; } finally { } } public static void main(String[] args) { new StopThreadTest().send(); } class TaskThread implements Callable<Object> { public Object call() throws Exception { for (int i = 0; i < 100000000; i++) { if (i % 100 == 0) i -= 50; if (isTO) System.out.println(i); } return true; } } }
为什么5秒后超时了任务线程还一直在运行??任务线程怎么终止了??这只是超时。
问题补充:xiaoZ5919 写道恩 是的 这是一个是超时,超过指定时间抛出timeoutexception,而不是终止,
你在taskThread执行的是死循环,这样的操作是对interrupt无效的,http://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html
并不是所有的方法可以被中断的,只有blocking的方法例如sleep,wait,join等被阻塞的方法,如果是一个长时间执行的方法是不会被中断,无论是用yx200404提供的future +timeout,本质懂事调用interrupt,有多几篇文章可以参考
http://www.ibm.com/developerworks/java/library/j-jtp05236/index.html
Implementing cancelable tasks
Just because a task is cancelable does not mean it needs to respond to an interrupt request immediately. For tasks that execute code in a loop, it is common to check for interruption only once per loop iteration. Depending on how long the loop takes to execute, it could take some time before the task code notices the thread has been interrupted (either by polling the interrupted status with Thread.isInterrupted() or by calling a blocking method). If the task needs to be more responsive, it can poll the interrupted status more frequently. Blocking methods usually poll the interrupted status immediately on entry, throwing InterruptedException if it is set to improve responsiveness.
所以根本不可能中断一个一直在运行的线程咯。2012年1月03日 17:18
14个答案 按时间排序 按投票排序
-
shutdownNow也是best-effort尽力而为,不一定能interrupt,就象你执行的这个死循环的任务,肯定中断不了
<p>There are no guarantees beyond best-effort attempts to stop
* processing actively executing tasks. This implementation
* cancels tasks via {@link Thread#interrupt}, so any task that
* fails to respond to interrupts may never terminate.2012年1月12日 15:09
-
忘记加上exec.shutdownNow();
和xiaoZ5919 说的一样.shutdownNow会尽可能的interrupt2012年1月12日 14:01
-
恩 是的 这是一个是超时,超过指定时间抛出timeoutexception,而不是终止,
你在taskThread执行的是死循环,这样的操作是对interrupt无效的,http://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html
并不是所有的方法可以被中断的,只有blocking的方法例如sleep,wait,join等被阻塞的方法,如果是一个长时间执行的方法是不会被中断,无论是用yx200404提供的future +timeout,本质懂事调用interrupt,有多几篇文章可以参考
http://www.ibm.com/developerworks/java/library/j-jtp05236/index.html
Implementing cancelable tasks
Just because a task is cancelable does not mean it needs to respond to an interrupt request immediately. For tasks that execute code in a loop, it is common to check for interruption only once per loop iteration. Depending on how long the loop takes to execute, it could take some time before the task code notices the thread has been interrupted (either by polling the interrupted status with Thread.isInterrupted() or by calling a blocking method). If the task needs to be more responsive, it can poll the interrupted status more frequently. Blocking methods usually poll the interrupted status immediately on entry, throwing InterruptedException if it is set to improve responsiveness.2012年1月09日 11:43
-
import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class A { //自己设置大小,这里设置的是一个单工作线程 final ExecutorService exec = Executors.newSingleThreadExecutor(); public void send() { TaskThread taskThread = new TaskThread(); Future<Object> taskFuture = exec.submit(taskThread); try { //此处看任务线程是否返回值,如果不返回,那么在1分钟后任务线程会被强行终止 taskFuture.get(1, TimeUnit.MINUTES); } catch (InterruptedException ex) { // } catch (ExecutionException ex) { // } catch (TimeoutException ex) { // } finally { } } class TaskThread implements Callable<Object> { public Object call() throws Exception { methodA(); methodB(); methodC(); methodD(); methodE(); return false; } } }
哥们些,什么年代了...还在自己搞"终止"处理~2012年1月07日 11:37
-
请忽略我写的用interrupt方法,中断完不成这个活儿
具体参照http://www.iteye.com/topic/9700552012年1月05日 14:10
-
当初我也有过楼主的困惑,其实回过头来想想,你出现了这种好几个方法的调用,还想要停止,对于JAVA是不可行的,从根儿上来说,设计的时候就有问题,建议重新设计这个地方,加入循环判断变量,好让其他线程可以终止此线程
2012年1月04日 22:07
-
如果是当前线程,而不是在另外一个线程中调用该线程,我觉得不用监控线程做不到,如是后者可用join(1000)然后线程是否alive,再调用interrupt中断这个线程如是当前线程可用spring+proxy调用方法的开始启动监控线程进行监控
2012年1月04日 21:44
-
你的service是否操作某些资源,比如IO、数据库连接等等,你可以在外部强制关闭资源,这样处理线程会抛出出异常而结束。这也算是一个方法吧
2012年1月04日 19:43
-
这个问题很多人问,告诉你吧,唯一可行的方法就是设置标志位,当超时到达时,改变标志位状态,然后任务线程每次进行任务之前根据标志位判断是否因该退出。
用stop等方法强行终止会使任务允许状态不可控。
设置标志位可以是自定义的变量,也可以是Thread的interrupte()方法,本质是一样的。
针对你的需求,目前只能这样做,但如果你给出详细的场景,也许有更好的方式解决问题。2012年1月04日 09:00
-
if (Thread.interrupted()) { if (Thread.interrupted()) { System.out.println("Interrupted..."); break; } }
连续两次检查我认为是不合理,在我看来没有什么意义。
现在主要是在监控器中用interpreted,stop早已经不推荐了 被干掉了。2012年1月03日 20:23
-
看看下面这个能不能满足你的需求:
public class HelloWorld { public static void main(String[] args) throws Exception { System.out.println("---------------------------------------"); // “Test2" Thread th2 = new Thread(new Test2()); // 启动 Test2 线程,并在3秒之后中断该线程。 th2.start(); Thread.yield(); System.out.println("Interrupting Test2..."); th2.interrupt(); Thread.yield(); // 主线程结束。 System.out.println("End of main."); } private static class Test2 implements Runnable { public void run() { // 记录线程开始时间。 long startTime = System.currentTimeMillis(); System.out.println("Test2 start... " + "Automatically ends in 6 sec."); while (true) { // 连续判断2次Thread.interrupted() if (Thread.interrupted()) { if (Thread.interrupted()) { System.out.println("Interrupted..."); break; } } // 如果线程2运行超过6秒将自动结束。 if (System.currentTimeMillis() - startTime > 6000) { System.out.println("5 seconds..."); break; } } System.out.println("Test2 end"); } } }
2012年1月03日 19:40
相关推荐
总结来说,虽然Java中`Thread.stop()`方法可以强制停止线程,但由于其潜在的风险,不应使用。推荐采用`Thread.interrupt()`结合`isInterrupted()`/`interrupted()`的方式来安全地中断线程,确保资源的正确释放和程序...
#### 一、为什么不能强制停止线程? 在Java早期版本中,提供了`Thread.stop()`方法来直接终止线程,但这种方法存在严重的安全问题。例如,它可能会导致对象处于不稳定的状态,或者在对象的某些关键操作(如资源释放...
- 终止(Terminated):线程执行完成或被强制停止。 6. **线程优先级**: - Java的线程有10个优先级,`Thread.MIN_PRIORITY`(1)、`Thread.NORM_PRIORITY`(5,默认值)和`Thread.MAX_PRIORITY`(10)。优先级较...
Thread类提供了interrupt()方法用于中断线程,但需要注意的是,这并不意味着线程会立即停止,而是在线程检查到中断标志后自行决定是否停止。守护线程(Daemon Thread)是一种特殊线程,当所有非守护线程结束时,守护...
值得注意的是,这个例子中使用了`stop()`方法来强制停止线程,但这是不推荐的,因为它可能会导致数据不一致和资源泄漏。在Java中,应该使用更安全的方式来中断线程,比如设置共享变量、使用`interrupt()`方法或抛出...
通常不建议直接使用`stop()`或`destroy()`方法来强制停止线程,因为它们可能导致数据不一致和其他问题。 8. **线程池与Executor框架** Java 5引入了Executor框架,通过`ExecutorService`和`ThreadPoolExecutor`等...
强制停止则是通过调用`stop()`方法强制终止线程。 #### 线程调度 线程调度是指操作系统如何决定下一个要执行的线程。Java中的线程调度是基于优先级的,但也受到操作系统的调度策略的影响。Java线程的优先级可以通过...
- **终止**(TERMINATED):线程执行完毕或被强制停止。 3. **线程控制** - **join()**:让当前线程等待指定线程完成。 - **sleep()**:使当前线程暂停执行一段时间。 - **yield()**:让当前线程暂停,让其他...
- **终止**(Terminated):线程已完成其工作或者被强制停止。 #### 四、创建线程的几种方法 创建多线程程序的主要目的是为了实现任务的并发执行,提高程序的效率。在Java中,可以通过以下几种方式创建线程: 1. *...
6. **终止状态(Terminated)**:线程执行完毕或被强制停止。 线程调度策略包括:抢占式调度(优先级高的线程先执行)和协作式调度(线程自行决定何时放弃执行权)。Java中默认采用抢占式调度。 线程间的通信主要...
另一个是因异常退出 run() 方法或者外部强制停止。一旦线程进入死亡状态,它就不能再被唤醒执行。 Java 多线程技术是 Java 平台的核心特性之一,允许应用程序同时执行多个任务,提高系统的并发性和效率。在 Java 中...
- **Java线程的独特之处**: Java是首个在语言层面直接支持线程特性的主流编程语言,这意味着开发者可以直接在Java代码中管理线程而无需依赖底层操作系统接口。 #### 三、Java线程的生命周期 - **新建**(New): 当...
- **死亡状态**:线程完成执行或被强制终止后所处的状态。 - **阻塞的原因**包括但不限于: - 调用`suspend()`方法。 - 调用`sleep()`方法。 - 等待其他线程释放同步监视器(例如`wait()`)。 - 输入输出操作...
然而,Java的Thread类没有提供直接停止线程的方法,因为强制结束线程可能导致资源泄漏和其他问题。通常,我们通过设置共享标志或者中断请求来让线程自行终止。例如: ```java // 在线程的run()方法内 if ...
- **死亡**:线程执行完毕或者被强制停止。 ### 四、线程同步与死锁 #### 线程同步 - **定义**:线程同步是为了保证多个线程能够正确访问共享资源而采取的一种机制。主要使用`synchronized`关键字来实现。 - **...
需要注意的是,`sleep()`会强制停止执行,而`yield()`则可能不立即让出执行权。 线程同步是防止多个线程同时访问共享资源导致数据不一致的关键。Java提供了同步方法,通过`synchronized`关键字来实现,确保同一时刻...
4. **死亡状态**:线程完成其任务或被强制停止,不再执行。 #### 四、线程的优先级 线程的优先级影响其获取CPU时间片的概率。在Java中,线程的优先级可以通过`Thread`类的`setPriority()`方法设置,范围通常在1...
旧版本的Java API中,`Thread.stop()`方法用于强制停止线程,但因为可能引发数据不一致和资源泄露问题,已被废弃。在上述代码中,注释掉的`a.stop();`就是这种不推荐的用法。 4. **`wait()`, `join()`, `sleep()`...
- `stop()`:强制停止线程(已废弃,不推荐使用,可能导致数据不一致)。 - `interrupt()`:中断线程,设置线程的中断标志位。 - `isAlive()`:检查线程是否仍然处于活动状态。 - `isInterrupted()`:检查线程是否被...
- **终止**:线程执行完毕或者被强制停止。 - **线程控制方法**: - `start()`:启动线程。 - `stop()`:已废弃,不应再使用。 - `wait()`:释放对象锁,让当前线程进入等待状态,直到被唤醒。 - `sleep(long ...