Springboot单元测试
在Springboot@Test中,使用多线程时,是无法深度执行解析的。原因在junit单元测试使用的是守护线程。
守护线程:又叫精灵线程,是为非守护线程服务,类似在后台静默执行,比如:JVM垃圾回收机制。当只剩下守护线程时,JVM就会退出。我们新建Thread时,如果想要改成守护线程时,需要设置daemon为true,默认是false。
非守护线程:我们平常创建的普通线程
解决方案
- 使用Main()
public static void main(String[] args) throws IOException {
String mgs="Hello World";
char[] a="1234567".toCharArray();
char[] b="abcdefg".toCharArray();
PipedInputStream input1=new PipedInputStream();
PipedOutputStream out1=new PipedOutputStream();
PipedInputStream input2=new PipedInputStream();
PipedOutputStream out2=new PipedOutputStream();
input1.connect(out2);
input2.connect(out1);
new Thread("t1"){
@Override
public void run() {
byte[] bytes=new byte[9];
try{
for (char i: a) {
input1.read(bytes);
if (new String(bytes).equals(mgs)) {
System.out.println(i);
}
out1.write(mgs.getBytes());
}
}catch(Exception e){
e.printStackTrace();
}
}
}.start();
new Thread("t2"){
@Override
public void run() {
byte[] by=new byte[9];
try{
for (char o: b) {
System.out.println(o);
out2.write(mgs.getBytes());
input2.read(by);
if (new String(by).equals(mgs)) {
continue;
}
}
}catch(Exception e){
e.printStackTrace();
}
}
}.start();
}
- join()
@Test
void changMgs() throws IOException, InterruptedException {
String mgs="Hello World";
char[] a="1234567".toCharArray();
char[] b="abcdefg".toCharArray();
PipedInputStream input1=new PipedInputStream();
PipedOutputStream out1=new PipedOutputStream();
PipedInputStream input2=new PipedInputStream();
PipedOutputStream out2=new PipedOutputStream();
input1.connect(out2);
input2.connect(out1);
Thread t1= new Thread("t1"){
@Override
public void run() {
byte[] bytes=new byte[11];
try{
for (char i: a) {
input1.read(bytes);
if (new String(bytes).equals(mgs)) {
System.out.println(i);
}
out1.write(mgs.getBytes());
}
}catch(Exception e){
e.printStackTrace();
}
}
};
Thread t2= new Thread("t2"){
@Override
public void run() {
byte[] by=new byte[11];
try{
for (char o: b) {
System.out.println(o);
out2.write(mgs.getBytes());
input2.read(by);
if (new String(by).equals(mgs)) {
continue;
}
}
}catch(Exception e){
e.printStackTrace();
}
}
};
t1.start();
t2.start();
t1.join();
t2.join();
}
当然,还有其他方法,请自行百度下。只要保证主线程退出前子线程已经结束运行。
持之以恒,方能达到大道之巅
|