This article describes a small problem that occurs when using JUnit for threading testing, and makes a simple record of what you can do to see later
The test program was written in Juint when using Java to write multithreaded concurrent experiment programs, but did not get the desired effect.
Directly on the code
Thread class:
Package Sm.examples.threaddemo;import Org.apache.log4j.logger;public class Thread1 implements Runnable {private static Final Logger Logger = Logger.getlogger (thread1.class), @Overridepublic Void Run () {int i = 0;while (true) {Logger.info ("--- --in while------"+ i++"), try {thread.sleep (+),} catch (Interruptedexception e) {e.printstacktrace ();} if (i = =) {break;}}}}
Test class:
Package Sm.test;import Org.apache.log4j.logger;import Org.junit.test;import sm.examples.threaddemo.thread1;public Class Testthreaddemo {/** * Logger for this class */private static final Logger Logger = Logger.getlogger (testthreaddemo.c LASS); @Testpublic void Test () {Thread1 thread1 = new Thread1 (); thread T1 = new Thread (THREAD1); Thread t2 = new Thread (THREAD1); T1.start (); T2.start ();}}
Originally expected to execute after two threads will be alternately in the console print out 0-49, but actually just print out the
[Sm.examples.threaddemo.Thread1] [Thread-0]------in while------0
[Sm.examples.threaddemo.Thread1] [Thread-1]------in while------0
Test with the main function to achieve the desired effect. Think about it a little bit, it feels like the test method in the testing class starts with two threads and ends itself, so the thread that starts up cannot output the content in the console.
The code was modified to add a sleep wait in the test method, and the console output the desired effect.
Modified code:
Package Sm.test;import Org.apache.log4j.logger;import Org.junit.test;import sm.examples.threaddemo.thread1;public Class Testthreaddemo {/** * Logger for this class */private static final Logger Logger = Logger.getlogger (testthreaddemo.c LASS); @Testpublic void Test () {Thread1 thread1 = new Thread1 (); thread T1 = new Thread (THREAD1); Thread t2 = new Thread (THREAD1); T1.start (); T2.start (); try {logger.info ("in Test"); Thread.Sleep (10000);} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}
"Java" uses JUnit to test for minor problems during threading