我的BufferedReader从InputStreamReader (从InputStream读取)遇到了死锁问题。
有一个Swing GUI正在被用户关闭。正在释放JFrame并调用finish方法。
DppGUI gui = this;
addWindowListener(new WindowAdapter()
{
@Override
public void windowClosing(WindowEvent windowEvent)
{
int choice = Dialogs.displayExitQuestionDialog(gui);
if (choice == JOptionPane.YES_OPTION)
{
_dataReciever.finish();
dispose();
}
}
});需要运行finish方法才能中断while循环,从而最终让线程完成。这是完成的方法。
public void finish()
{
_isRunning = false; // This boolean shall break a while loop.
_listener = null;
try
{
_processInputStream.close();
System.out.println("Closed input stream");
_inputStreamReader.close();
System.out.println("Closed input stream reader");
_reader.close();
System.out.println("Closed reader");
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}问题是,我不知道如何从“外部”关闭BufferedReader,从而使行
while ((line = _reader.readLine()) != null)被跳过了。
下面是死锁的线程(一旦用户关闭gui,它就需要完成)。
@Override
public void run()
{
_isRunning = true;
CommandManager commandManager = new CommandManager();
Process process = null;
try
{
process = commandManager.makeCommand(MqttCoammands.MOSQUITTO_SUB,
"HFC_001", "");
System.out.println("Mosquitto Sub Command generated.");
_processInputStream = process.getInputStream();
_inputStreamReader = new InputStreamReader(_processInputStream);
_reader = new BufferedReader(_inputStreamReader);
String line = null;
while (_isRunning)
{
while ((line = _reader.readLine()) != null) // The program deadlocks in this line when the GUI is closed
{
String[] splits = line.split(";");
_parameterList = Arrays.asList(splits);
System.out.println(_parameterList.toString());
_listener.get(_parameterList);
}
}
System.out.println("Left the While loop. Preparing end of Thread.");
_listener = null;
// finish();
}
catch (IllegalCommandException e1)
{
e1.printStackTrace();
}
catch (UnsupportedOperatingSystemException e1)
{
e1.printStackTrace();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}要关闭BufferedReader,我尝试将其设置为null。我试图关闭BufferedReader、InputStreamReader和InputStream (正如您在finish方法中看到的那样),但是没有工作,程序仍然死锁。有人遇到过同样的问题吗?有人看到解决办法了吗?
提前感谢!
编辑:--我忘记提到死锁之前的最后一个控制台输出是
封闭输入流
它来自于完成方法。这意味着InputStreamReader和BufferedReader并不是封闭的。
发布于 2018-08-21 11:38:26
close调用。reader.readLine接收一个reader.readLine。发布于 2018-08-21 11:25:21
替换
while (_isRunning)
{
while ((line = _reader.readLine()) != null) // The program deadlocks in this line when the GUI is closed
{使用
while (_isRunning && (line = _reader.readLine()) != null)
{https://stackoverflow.com/questions/51947546
复制相似问题