以下处理方式有什么区别InterruptedException?最好的方法是什么?
try{
//...
} catch(InterruptedException e) {
Thread.currentThread().interrupt();
}
Run Code Online (Sandbox Code Playgroud)
要么
try{
//...
} catch(InterruptedException e) {
throw new RuntimeException(e);
}
Run Code Online (Sandbox Code Playgroud)
编辑:我也想知道这两个使用的场景.
java multithreading exception-handling interrupted-exception
我需要一个解决方案来正确地停止Java中的线程.
我有IndexProcessor实现Runnable接口的类:
public class IndexProcessor implements Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(IndexProcessor.class);
@Override
public void run() {
boolean run = true;
while (run) {
try {
LOGGER.debug("Sleeping...");
Thread.sleep((long) 15000);
LOGGER.debug("Processing");
} catch (InterruptedException e) {
LOGGER.error("Exception", e);
run = false;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我有ServletContextListener开始和停止线程的类:
public class SearchEngineContextListener implements ServletContextListener {
private static final Logger LOGGER = LoggerFactory.getLogger(SearchEngineContextListener.class);
private Thread thread = null;
@Override
public void contextInitialized(ServletContextEvent event) {
thread = new Thread(new …Run Code Online (Sandbox Code Playgroud) 为什么Thread.stop()在Java中被弃用?在他们的网站上,我看到以下内容:
为什么
Thread.stop弃用?因为它本质上是不安全的.停止线程会导致它解锁已锁定的所有监视器.(当
ThreadDeath异常传播到堆栈中时,监视器将被解锁.)如果先前受这些监视器保护的任何对象处于不一致状态,则其他线程现在可以以不一致的状态查看这些对象.据说这些物体已被损坏.当线程对受损对象进行操作时,可能会导致任意行为.这种行为可能很微妙并且难以检测,或者可能是明显的.与其他未经检查的异常不同,它会ThreadDeath默默地杀死线程; 因此,用户没有警告他的程序可能被破坏.腐败可以在实际损害发生后的任何时间显现,甚至在未来几小时或几天.
我不明白"监视器"是什么意思.无论如何,我的问题是如果Thread.stop()不应该调用那么Java线程应该如何停止?
如何在java中停止或中断睡眠线程?我有一个同步数据并在run()方法中休眠10分钟的线程,如果我想通过在线程休眠时停止线程来停止同步.怎么能实现这一目标?
我试图阻止一个线程,但我不能这样做:
public class Middleware {
public void read() {
try {
socket = new Socket("192.168.1.8", 2001);
// code ..
Scan scan = new Scan();
thread = new Thread(scan);
thread.start();
} catch (UnknownHostException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
class Scan extends Thread {
public void run() {
while (true) {
try {
// my code goes here
} catch (IOException ex) {
thread.currentThread().interrupt();
}
}
}
}
public void stop() {
Thread.currentThread().interrupt();
}
// get …Run Code Online (Sandbox Code Playgroud) Apache Tomcat多次说:
Web应用程序[/ MyServlet]似乎已启动名为[pool-61-thread-2]的线程,但未能将其停止.这很可能造成内存泄漏.
这有危险吗?servlet应该能够处理10.000个请求/天.完成后如何关闭线程?
class Worker {
private final CountDownLatch startSignal;
private final CountDownLatch doneSignal;
private final int threadNumber;
Worker(
CountDownLatch startSignal,
CountDownLatch doneSignal,
int threadNumber
){
this.startSignal = startSignal;
this.doneSignal = doneSignal;
this.threadNumber = threadNumber;
}
public String[][] getSomeStrArrArr() {
String[][] isRs = new String[8][20];
String[][] inRs = new String[8][20];
String[][] iwRs = new String[8][20];
try {
startSignal.await();
if (threadNumber == 1) {
// get String[][] result for thread number 1
isRs = getIS(erg1, erg2, request);
}
if …Run Code Online (Sandbox Code Playgroud) 我遇到过下面的代码,我想知道它是否完全符合我的想法:
synchronized(sObject) {
mShouldExit = true;
sObject.notifyAll()
while (!mExited) {
try {
sObject.wait();
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
Run Code Online (Sandbox Code Playgroud)
关于上下文:还有另一个线程检查mShouldExit(在sObject监视器内)并在这种情况下退出.
这看起来对我来说不是一个正确的模式.如果发生中断,它将再次设置中断状态,所以当它返回时sObject.wait(),会出现另一个InterruptedException等等.因此,它永远不会进入真正的等待状态(sObject.wait()),即它永远不会释放sObject监视器.这可能导致无限循环,因为另一个线程无法将mExiting设置为true,因为它永远不会进入sObject的监视器.(所以我认为这个interrupt()电话是错误的,不能在这里使用.)我错过了什么吗?
请注意,代码段是官方Android框架源代码的一部分.
更新:实际上,情况更糟,因为在GL渲染开始时Android中使用了相同的模式.官方源代码GLSurfaceView.GLThread.surfaceCreated():
public void surfaceCreated() {
synchronized(sGLThreadManager) {
if (LOG_THREADS) {
Log.i("GLThread", "surfaceCreated tid=" + getId());
}
mHasSurface = true;
sGLThreadManager.notifyAll();
while((mWaitingForSurface) && (!mExited)) {
try {
sGLThreadManager.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
您可以用类似的方式重现错误:确保您的UI线程还有其中断状态标志,然后添加您的GLSurfaceView并启动GL渲染(通过setRenderer(...),但在某些设备上,确保您的GLSurfaceView具有 …
我有一个Java带有run方法的线程来计算很多东西.您可以将其视为一系列数学语句,如下所示.注意,每个计算可以使用其他方法,这些方法又可以具有额外的循环等.
public void run() {
[computation 1 goes here here that takes a few seconds]
[computation 2 goes here that takes a few seconds]
....
[computation 30 goes here that takes a few seconds]
}
Run Code Online (Sandbox Code Playgroud)
有一个GUI打印这些语句的输出,因为它们产生了结果,我希望用户能够随时说"停止".这是我想到的两种方法
方法1:许多布尔检查[LOOKS TERRIBLE]
private boolean stop;
public void run() {
if(!stop)
[computation 1 goes here here that takes a few seconds]
if(!stop)
[computation 2 goes here that takes a few seconds]
....
if(!stop)
[computation 30 goes here that takes a few …Run Code Online (Sandbox Code Playgroud) 我一直在寻找杀死线程的方法,看起来这是最流行的方法
public class UsingFlagToShutdownThread extends Thread {
private boolean running = true;
public void run() {
while (running) {
System.out.print(".");
System.out.flush();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {}
}
System.out.println("Shutting down thread");
}
public void shutdown() {
running = false;
}
public static void main(String[] args)
throws InterruptedException {
UsingFlagToShutdownThread t = new UsingFlagToShutdownThread();
t.start();
Thread.sleep(5000);
t.shutdown();
}
}
Run Code Online (Sandbox Code Playgroud)
但是,如果在while循环中我们生成了另一个被数据填充的对象(比如运行和更新的gui),那么我们如何回调 - 特别是考虑到这个方法可能已被多次调用,所以我们有很多线程而(运行)然后更改一个标志将改变它为每个人?
谢谢
java ×10
multithreading ×10
android ×1
concurrency ×1
listener ×1
memory-leaks ×1
servlets ×1
sleep ×1
tomcat ×1