i am trying to perform whats inside the while condition but when the condition ends the threads keep on going check the output i need to stop whats inside the while loop according to the timer basically doing the timer's job
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");
output
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)
This is what the above code does:
UserGenerator and one thread of Vote per secondSo, after 10 seconds, while loop will end and main thread will exit. However, 5 threds started by it will continue to run (until their run method finishes or an exception is thrown). It depends on how run method is implemented in UserGenerator and Vote classes. E.g. if there's an infinite loop, those threads will continue to run and the program will never exit.
I am not sure I have enough information for a full answer, however you can try this:
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");
}