用来测试线程同步问题的代码:
[code="java"]
public class SynchronizeDemo {
private static final int ticks = 10;
private static double tickets = ticks;
private static double price = 5;
private static double total = 0;
private static boolean print = true;
public static void main(String[] args) {
System.out.println(Thread.currentThread());
System.out.println(Thread.currentThread().isDaemon());
new saller().start();
new saller().start();
new saller().start();
// while(tickets != 0) {
// }
}
@Test
public void test() {
// Thread daeom = new daemont();
// daeom.setDaemon(true);
// daeom.start();
System.out.println(Thread.currentThread());
System.out.println(Thread.currentThread().isDaemon());
new saller().start();
new saller().start();
new saller().start();
}
public static class saller extends Thread {
@Override
public void run() {
while(tickets != 0) {
tickets -= 1;
total += price;
// System.out.println(getName() + ": " + tickets + " left, total=" + total);
System.out.println(
Thread.currentThread() + ": " + tickets + " left, total="
+ total);
try {
Thread.sleep(100);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
if(tickets == 0 && print) {
System.out.println("Total should be :" + 5 * ticks + "; ");
print = false;
}
}
}
// public static class daemont extends Thread {
// @Override
// public void run() {
// while(true) {
// System.out.println("I`m a daemon....");
// try {
// Thread.sleep(1000);
// } catch(InterruptedException e) {
// e.printStackTrace();
// }
// }
// }
// }
}
[/code]
测试结果如下:
1. 在 main 方法中开启三个线程, 如果 main 方法结束(主线程结束--Thread[main,5,main]),子线程不会结束继续运行;
2. 在 @Test 方法中开启三个线程, 如果 @Test 方法结束, 子线程也会结束(每个子线程仅输出一次...);
在两种情况中 子线程的 toString() 结果都一致:
Thread[Thread-0,5,main]
Thread[Thread-1,5,main]
Thread[Thread-2,5,main]
请问这是为什么? 为什么在 Junit 框架下的 @Test 方法中开启的子线程会在测试方法结束时一并结束??
尝试过在 @Test 方法中添加一个 守护线程, 但是无效....