Reputation: 16057
I have a button, that when pressed, should create an instance of a new thread: a Countdown Timer. The problem is, I need to do this with some kind of dynamic array, because there is no way of knowing how many times the user will press the button!
This is the code in the button's action listener:
Counter c = new Counter(timeToFinish);
This is the code for the Counter class:
class Counter implements Runnable {
int waitingTime = 0;
Thread myCounter = new Thread(this);
public Counter(int waitingTime)
{
this.waitingTime = waitingTime;
myCounter.start();
}
public void run(){
//Start countdown:
do
{
waitingTime -= 1;
try {
Thread.sleep(1000);
System.out.println(waitingTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (waitingTime >= 0);
}
}
If the user presses the button ten times, ten instances should be created, from c(0) to c(9), each separate threads. I don't know how to create a dynamic array of threads :S
Upvotes: 1
Views: 191
Reputation: 240928
Create a storage list
List<Counter> lst = new ArrayList<Counter>();
add thread to list, on click
Counter counter = new Counter(someInt);
lst.add(counter );
Also try to manage deleting reference of thread from List
Upvotes: 1
Reputation: 421090
I need to do this with some kind of dynamic array
Try using an ArrayList
.
If the user presses the button ten times, ten instances should be created, from c(0) to c(9), each separate threads. I don't know how to create a dynamic array of threads :S
Something like this should do:
Create a List
to store the counters:
List<Counter> myCounters = new ArrayList<Counter>();
Add new counter-threads like this:
int nexti = myCounters.size();
myCounters.add(new Counter(nexti));
Upvotes: 2
Reputation: 4748
I would definitely not be creating a new Thread every time the user clicked a button. If they click it a few hundred times your application might die or slow down. When they click the button you know what time you want your Timer to expire. So rather create a Timer object and put that on an ordered queue (ordered from earliest to latest expiry time) and then have a single Thread monitoring that queue, popping off Timers as they expire.
Your TimerWatcher thread can then wake up every few milliseconds, or better, wait until it knows the first Timer is going to expire and then peak at the next Timer and wait until this next one expires. Whenever you add a new Timer you can also wake up your TimerWatcher and check that the new Timer has not expired to that it doesn't expire before the one you were already waiting for.
Upvotes: 0