我试图在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)
答案 0 :(得分:0)
以上代码的作用如下:
UserGenerator
的一个帖子和每秒Vote
的一个帖子因此,10秒后,while
循环将结束,main
线程将退出。但是,由它启动的5 threds
将继续运行(直到它们的run
方法完成或抛出异常)。这取决于run
和UserGenerator
类中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");
}