Изменить: см. здесь!
У меня есть поток с Runnable, показанный ниже. С этим есть проблема, которую я не могу понять: в половине случаев, когда я вызываю interrupt()
в потоке (чтобы остановить его), он фактически не завершается (InterruptedException
не перехватывается).
private class DataRunnable implements Runnable {
@Override
public void run() {
Log.d(TAG, "DataRunnable started");
while (true) {
try {
final String currentTemperature = HeatingSystem.get("currentTemperature");
mView.post(() -> showData(currentTemperature));
} catch (ConnectException e) {
mView.post(() -> showConnectionMessage());
break;
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
break;
}
}
Log.d(TAG, "DataRunnable terminated");
}
}
Проблема заключается в методе HeatingSystem.get(String)
, который выполняет длительную сетевую операцию. Я предполагаю, что где-то в этом методе флаг прерывания сбрасывается, но я не могу найти, какой оператор будет это делать (я не нашел упоминания об этом в справочниках для всех классов, участвующих в методе, например HttpURLConnection
). Способ ниже (написан не мной).
/**
* Retrieves all data except for weekProgram
* @param attribute_name
* = { "day", "time", "currentTemperature", "dayTemperature",
* "nightTemperature", "weekProgramState" }; Note that
* "weekProgram" has not been included, because it has a more
* complex value than a single value. Therefore the funciton
* getWeekProgram() is implemented which return a WeekProgram
* object that can be easily altered.
*/
public static String get(String attribute_name) throws ConnectException,
IllegalArgumentException {
// If XML File does not contain the specified attribute, than
// throw NotFound or NotFoundArgumentException
// You can retrieve every attribute with a single value. But for the
// WeekProgram you need to call getWeekProgram().
String link = "";
boolean match = false;
String[] valid_names = {"day", "time", "currentTemperature",
"dayTemperature", "nightTemperature", "weekProgramState"};
String[] tag_names = {"current_day", "time", "current_temperature",
"day_temperature", "night_temperature", "week_program_state"};
int i;
for (i = 0; i < valid_names.length; i++) {
if (attribute_name.equalsIgnoreCase(valid_names[i])) {
match = true;
link = HeatingSystem.BASE_ADDRESS + "/" + valid_names[i];
break;
}
}
if (match) {
InputStream in = null;
try {
HttpURLConnection connect = getHttpConnection(link, "GET");
in = connect.getInputStream();
/**
* For Debugging Note that when the input stream is already used
* with this BufferedReader, then after that the XmlPullParser
* can no longer use it. This will cause an error/exception.
*
* BufferedReader inn = new BufferedReader(new
* InputStreamReader(in)); String testLine = ""; while((testLine
* = inn.readLine()) != null) { System.out.println("Line: " +
* testLine); }
*/
// Set up an XML parser.
XmlPullParser parser = Xml.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES,
false);
parser.setInput(in, "UTF-8"); // Enter the stream.
parser.nextTag();
parser.require(XmlPullParser.START_TAG, null, tag_names[i]);
int eventType = parser.getEventType();
// Find the single value.
String value = "";
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.TEXT) {
value = parser.getText();
break;
}
eventType = parser.next();
}
return value;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
System.out.println("FileNotFound Exception! " + e.getMessage());
// e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null)
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
// return null;
throw new IllegalArgumentException("Invalid Input Argument: \""
+ attribute_name + "\".");
}
return null;
}
/**
* Method for GET and PUT requests
* @param link
* @param type
* @return
* @throws IOException
* @throws MalformedURLException
* @throws UnknownHostException
* @throws FileNotFoundException
*/
private static HttpURLConnection getHttpConnection(String link, String type)
throws IOException, MalformedURLException, UnknownHostException,
FileNotFoundException {
URL url = new URL(link);
HttpURLConnection connect = (HttpURLConnection) url.openConnection();
connect.setReadTimeout(HeatingSystem.TIME_OUT);
connect.setConnectTimeout(HeatingSystem.TIME_OUT);
connect.setRequestProperty("Content-Type", "application/xml");
connect.setRequestMethod(type);
if (type.equalsIgnoreCase("GET")) {
connect.setDoInput(true);
connect.setDoOutput(false);
} else if (type.equalsIgnoreCase("PUT")) {
connect.setDoInput(false);
connect.setDoOutput(true);
}
connect.connect();
return connect;
}
Кто-нибудь знает, что в методе выше может вызвать проблему?
Thread.sleep()
также выдает InterruptException
, когда interrupt()
вызывается перед вводом Thread.sleep()
: () с установленным *статусом прерывания*? .
Я проверил, достигается ли Thread.sleep()
после прерывания, и он достигается.
Вот как DataRunnable запускается и прерывается (я всегда получаю журнал "onPause call"):
@Override
public void onResume() {
connect();
super.onResume();
}
@Override
public void onPause() {
Log.d(TAG, "onPause called");
mDataThread.interrupt();
super.onPause();
}
private void connect() {
if (mDataThread != null && mDataThread.isAlive()) {
Log.e(TAG, "mDataThread is alive while it shouldn't!"); // TODO: remove this for production.
}
setVisibleView(mLoading);
mDataThread = new Thread(new DataRunnable());
mDataThread.start();
}
if (Thread.currentThread().isInterrupted()) break;
перед Thread.sleep(), но проблема не устранена. - person mhvis   schedule 17.06.2015HeatingSystem.get(String)
. Однако я не полностью отлаживал этот метод, сделаю это. Кстати,connect()
вызывается только один раз. - person mhvis   schedule 18.06.2015Thread.currentThread().interrupt();
в самом начале методаDataRunnable
run()
. Затем я добавлял кучуSystem.out.println("line XX - " + Thread.currentThread().isInterrupted());
утверждений повсюду. Таким образом, я сужу линию, в которой состояние прерывания внезапно меняется на ложное. Надеюсь это поможет. (или вместо печати просто отлаживайте каждую строку, наблюдая за значениемisInterrupted()
) - person sstan   schedule 18.06.2015run()
, но кажется, что подсказка ведет к причине. Я получаю трассировку стека прямо сейчас сjava.io.InterruptedIOException
в строкеin = connect.getInputStream();
. Я еще не знаю, почему я не видел этого раньше, вероятно, потому, что вызовы прерывания в случайные моменты в основном относятся к самому длинному оператору, в который момент, по-видимому,printStackTrace()
не вызывается. Я напишу больше позже. - person mhvis   schedule 18.06.2015