Sunday, 15 July 2012

multithreading - Interrupt a thread safely in Java -


is a thread that connects to the server (HTTP) and waits for response or response timeout (server until Returns a loop does not respond to the data to return) When a thread processing is returned in response

There is a need to stop / interrupt all threads on the Stop service, but threads have to complete the response processing (if there is a thread processing and not waiting for the response).

Here is an example of code

  Public square waiting Response thread thread extension extended {Fixed final end TIMEOUT = 4 * 1000; Fixed final distance PROCESSING_DURATION = 2000; Private volatile bullion stops = false; Private volatile bullion processing = false; Run public void () {System.out.println ("initial hair thread"); While (Stop!) {Try {// here is waiting for a thread server response (real life response timeout in 400 seconds) // Probably it is now safe to interrupt the thread. Sleep () is simulating with the system. Out.println ("Waiting for response"); Thread.Sleep (timeout); Processing = true; // There is some work on the response and we will be allowed to terminate it / thread again. Imitate the delay with sleep () Thread.sleep (PROCESSING_DURATION); Processing = false; } Grip (Interrupted e) e.printStackTrace (); }} System.out.println ("Child Thread Ends"); } Public Zero Set Off (Boolean Closed) {this.stopped = Closed; } Public Boolean Processing () {Return Process; } Public static zero main (string [] args) {Waiting responseTr = new waiting response;); // Start thread, it sends a request and is waiting for the response to t.start (); Try {Thread.sleep (1); // Let's allow thread to end normally, if this response is for processing, set (true); System.out.println ("Waiting for the child to get a response"); Thread Sleep (TIMEOUT + 1); // Let's allow thread to finish processing (T. Processing ()) {System.out.println ("Processing"); Thread.Sleep (500); } // We can not wait up to 400 seconds until the next loop check / so that the thread is sleeping if we are obstructing it in bus (T. aslive ()) {System.out.println ("killing"); T.interrupt (); }} Grip (Interrupted e) e.printStackTrace (); } System.out.println ("main thread terminated"); }}  

Is this "hindering" method good? Is there another way to wait as time to time and to lose data that is processed?

this

  while (processing. ()) {System .out.println ("Processing"); Thread.Sleep (500); }  

There is a form of voting that you should avoid voting at all costs. If possible, use a form of delegation where the collar indicates the collar during processing.

Besides, I'm pretty sure that interfering with a thread is something that you hardly want to do, but the way you are doing it is okay if you have to do it anyway.


No comments:

Post a Comment