Problem finding
Recently in the review of multithreading related knowledge, the results of a hands-on problem, the problem is that in unit testing using multithreaded testing, found that as long as the child thread in the sleep period, the program will quit, no symptoms!!!!
Look at my code (please don't be stuck with the concurrency problem that this code brings):
public class threadtest{ class mythread implements Runnable{ private int count = 0 ; public void run () { try{ thread.sleep (; // ) child thread sleeps for one second, program exits }catch (interruptedexcetption e ) { e.printstacktrace (); } while (COUNT&NBSP;<&NBSP;15) { count ++; system.out.println (count); } } } @Test public void threadtest () { MyThread m1 = new MyThread (); thread t1 = new thread (M1); thread t2 = new thread (M1); thread t3 = new thread (M1); t1.start (); // Child Thread t2.start (); // sub-thread t3.start (); // sub-thread system.out.println (Thread.CurrentThread (). GetName ()); // main thread }
Problem analysis
The final check of the data only found:
This is the unit test bug, if you put the same program in main to run the problem will not occur!
Specific JUnit source code I don't know, but that's the way it is: You print out the name of the current thread in the unit test is actually main,
Then if the thread is turned on in the unit test, if the thread is running, then even if the unit test run is complete,
The child thread does not exit;
However, if the child thread is in a blocked, extinct state, the unit test immediately stops all child threads and exits the program!
Problem solving
1) If the child thread is not in a blocking state, the child thread will not exit even if the unit test run is complete;
2) You can force all child threads to run after the completion of the main thread, the following code:
T1.start (); Child thread T2.start (); Child thread T3.start (); Child thread T3.join (); After all child threads are guaranteed to run, run the following code System.out.println (Thread.CurrentThread (). GetName ()); Main thread
3) Not applicable unit test multi-threading, test with main
Multithreading quits without reason in Java unit tests