计时器在指定的时间后继续

时间:2017-04-29 10:06:46

标签: java multithreading timer

我试图在while条件下执行什么但是当条件结束时线程继续检查输出我需要根据计时器基本上执行计时器的工作来停止在while循环内的什么

 public static long start = System.currentTimeMillis();
    public static long end = start + 10 * 1000; // 10 seconds * 1000 ms/sec  

   while (System.currentTimeMillis() <= end) {
                    Thread t = new Thread(new UserGenerator());
                    Thread t1 = new Thread(new Vote());
                    t.start();
                    Thread.sleep(1000);
                    t1.start();
                    Thread.sleep(1000);
            }
            System.err.println("Time Done");

输出

Name:Alaine,Email:lg@shapirosher.com   ,SSN:516517   
Name:Adriana,Email:donbenchoff@comcast.net ,SSN:526527  
    Time Done
    User 516517   Voted
    User 526527   Voted
    BUILD SUCCESSFUL (total time: 16 seconds)

2 个答案:

答案 0 :(得分:0)

以上代码的作用如下:

  • 执行10秒
  • 产生UserGenerator的一个帖子和每秒Vote的一个帖子
  • 之间进入睡眠状态

因此,10秒后,while循环将结束,main线程将退出。但是,由它启动的5 threds将继续运行(直到它们的run方法完成或抛出异常)。这取决于runUserGenerator类中Vote方法的实现方式。例如。如果有无限循环,那些线程将继续运行,程序将永远不会退出。

答案 1 :(得分:0)

我不确定我是否有足够的信息来获得完整答案,但您可以尝试这样做:

    long start = System.currentTimeMillis();
    long end = start + (10 * 1000); // 10 seconds * 1000 ms/sec

    List<UserGenerator> us = new ArrayList<>();
    List<Vote> vs = new ArrayList<>();

    Thread  t, t1; 
    while (System.currentTimeMillis() <= end) {
        UserGenerator u; Vote v;

        t = new Thread( u = new UserGenerator());
        t1 = new Thread(v = new Vote());
        t.start();
        us.add(u);

        if(end - System.currentTimeMillis() >= 1000)
                            Thread.sleep(1000);

        t1.start();
        vs.add(v);

        if(end - System.currentTimeMillis() >= 1000)
        Thread.sleep(1000);
    }

    t.interrupt(); t1.interrupt();

    //the following may be redundant. It depends in what
    // UserGenerator and Vote do 
    for(int i =0; i < us.ssize() ; i++) {
        us.get(i).stop();
        vs.get(i).stop();
    }

    System.err.println("Time Done");
}
    long start = System.currentTimeMillis();
    long end = start + (10 * 1000); // 10 seconds * 1000 ms/sec

    List<UserGenerator> us = new ArrayList<>();
    List<Vote> vs = new ArrayList<>();

    Thread  t, t1; 
    while (System.currentTimeMillis() <= end) {
        UserGenerator u; Vote v;

        t = new Thread( u = new UserGenerator());
        t1 = new Thread(v = new Vote());
        t.start();
        us.add(u);

        if(end - System.currentTimeMillis() >= 1000)
                            Thread.sleep(1000);

        t1.start();
        vs.add(v);

        if(end - System.currentTimeMillis() >= 1000)
        Thread.sleep(1000);
    }

    t.interrupt(); t1.interrupt();

    //the following may be redundant. It depends in what
    // UserGenerator and Vote do 
    for(int i =0; i < us.ssize() ; i++) {
        us.get(i).stop();
        vs.get(i).stop();
    }

    System.err.println("Time Done");
}