java如何在一个线程可能尚未初始化时关闭另一个线程
我试图用java实现Linux pipe operator |
。基本思想是将连接的PipedInputStream
和PipeOutputStream
分配给这两个命令,它们可以同时执行它们的操作。
实施情况如下:
PipedOutputStream pOutputStream = new PipedOutputStream();
PipedInputStream pInputStream = new PipedInputStream();
pOutputStream.connect(pInputStream);
Thread thread1, thread2;
thread1 = new Thread(){
public void run() {
try {
new Call(pipe.cmd1).eval(CommandHandler.this, inputStream, pOutputStream);
pOutputStream.close();
} catch (Exception e) {
thread2.interrupt(); // cannot do this as it may not have been initialized
}
}
};
thread2 = new Thread() {
public void run() {
try{
new Pipe(pipe.cmd2).eval(CommandHandler.this, pInputStream, outputStream);
// pInputStream.close();
} catch (Exception e) {
// kill the first thread when the second one raises an exception
thread1.interrupt();
throw e;
}
}
};
thread1.start();
thread2.start();
// waiting for the two threads to die before carry on
thread2.join();
thread1.join();
我想在第一个线程引发异常时中断第二个线程,就像我在thread2 catch
中所做的那样。问题是thread2
分配给后者,因此我无法在thread1中访问它。我试图用空值将thread1&2
初始化,但它们必须是最终值,因为它们位于封闭范围内
如果这是一个愚蠢的问题,请原谅,我刚刚开始探索java中的多线程
**更新**
多亏了菲尔的建议。我将两个匿名内部类更改为两个扩展Thread
的内部类
class Thread1 extends Thread{
public Thread counterThread;
public void run() {
try {
new Call(pipe.cmd1).eval(CommandHandler.this, inputStream, pOutputStream);
pOutputStream.close();
} catch (Exception e) {
// kill thread 2
if (counterThread != null) counterThread.interrupt();
}
}
public void setThread(Thread thread) {
counterThread = thread;
}
};
class Thread2 extends Thread {
public Thread counterThread;
public void run() {
try{
new Pipe(pipe.cmd2).eval(CommandHandler.this, pInputStream, outputStream);
// pInputStream.close();
} catch (Exception e) {
// kill the first thread when the second one raises an exception
if (counterThread != null) counterThread.interrupt();
throw e;
}
}
public void setThread(Thread thread) {
counterThread = thread;
}
};
Thread1 thread1 = new Thread1();
Thread2 thread2 = new Thread2();
thread1.setThread(thread2);
thread2.setThread(thread1);
# 1 楼答案
考虑到您开始使用的代码,我想到了两种可能性。也许有更好的想法,但它们是:
(1)在匿名内部类定义中添加一个额外的公共方法,该方法允许您存储对要发送消息/中断的外部线程的引用。创建两个线程后,将每个线程的引用存储在另一个线程中
(2)存储对类的引用(可能是创建和启动线程的同一类),该类将保存对每个线程的引用。让
catch
方法调用该启动类中的一个方法,该方法将发送消息(通过松耦合模式)或中断对方