Reputation: 2470
I have a Thread (let's say T1) which reads data from socket:
public void run() {
while (running) {
try {
BufferedReader reader = new BufferedReader( new InputStreamReader(socket.getInputStream()) );
String input = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Another Thread (lets say T2) try to finish the program in one of its method. Therefore T2 does the following:
T1.running = false;
socket.close();
Here is this scenario for which i couldn't find a solution:
PS: "Another question about the Thread Debugging"
Normally when i debug the code step by step, i lose the 'active running line' on a context switch. Let's say i'm in line 20 of T1, context switch happens, let's assume the program continues from the 30.line of T2, but the debugger does not go/show to the 30.line of T2, instead the 'active running line' vanishes. So i lose the control over the code. I use Eclipse for Java and Visual Studio for C#. So what is the best way to track the code while debugging on a context switch ?
Upvotes: 0
Views: 3258
Reputation: 310909
Your code has several other problems so I'll address them all at the same time.
BufferedReader
outside the loop. Otherwise you will lose data in the buffers being discarded each time around the loop.readLine()
for null. If you get it, you must close the BufferedReader
and exit the loop.BufferedReader
and exit the loop.What i want is to catch this SocketException.
So catch it.
I can't put a try/catch(SocketException) in T1.run().
You must. No choice. You have to completely rewrite it anyway because of the above items.
Upvotes: 1
Reputation: 164
For your problem assuming you are using a Thread Pool maybe you should make a ThreadFactory that installs a Thread.UncaughtExceptionHandler on all Threads and then invoke your work with execute() on the ExecutorService instead of submit().
For you problem with debugging maybe you should read http://msdn.microsoft.com/en-us/library/ms164746.aspx
Upvotes: 1