weixin_42352270 2009-12-19 23:03
浏览 362
已采纳

在main方法中开启线程与@Test中开启线程

用来测试线程同步问题的代码:
[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 方法中添加一个 守护线程, 但是无效....

  • 写回答

1条回答 默认 最新

  • CaiHuajiang 2009-12-20 11:39
    关注

    应该比较好理解的吧,@Test会在方法运行完后对请求的资源进行统一的释放。
    当然,具体怎么实现的我想要看源码才知道了。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 C#调用python代码(python带有库)
  • ¥15 矩阵加法的规则是两个矩阵中对应位置的数的绝对值进行加和
  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)
  • ¥20 怎么在stm32门禁成品上增加查询记录功能
  • ¥15 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面