I have problem with printing out the each value of certain array with certain duration of time. For example I have array with values: "Value1", "Value2", "Value3". I want to o开发者_StackOverflow中文版utput "Value1", after 5 sec "Value2", after 5 second "Value3". Instead, All Values of arrays are printout 3 times. If you could help to me, I will be so gratefull )) Thank you.
Here is my code.
import java.util.Date;
public class Timer2 {
/**
* @param args
*/
public static void main(String[] args) {
long start = new Date().getTime();
for (int i = 0; i < 4; i++) {
new java.util.Timer().schedule(new java.util.TimerTask() {
public void run() {
String[] arrayElements = { "value1", "value2", "value3",
"value4" };
for (int i = 0; i < arrayElements.length; i++)
System.out.println(arrayElements[i]);
}
}, new Date(start));
start += 1000;
}
}
}
Solution from my answer in cross-post that uses scheduleAtFixedRate:
import java.util.Timer;
import java.util.TimerTask;
class Timer2 {
private static final String[] ARRAY_ELEMENTS = {"value1", "value2", "value3", "value4"};
public static void main(String[] args) {
final Timer utilTimer = new Timer();
utilTimer.scheduleAtFixedRate(new TimerTask() {
private int index = 0;
public void run() {
System.out.println(ARRAY_ELEMENTS[index]);
index++;
if (index >= ARRAY_ELEMENTS.length) {
utilTimer.cancel();
}
}
}, 5000L, 5000L);
}
}
The simplest way to do what you have described you want to do is:
public static void main(String[] args) throws InterruptedException {
String[] arrayElements = { "value1", "value2", "value3", "value4" };
for (int i = 0; i < arrayElements.length; i++) {
System.out.println(arrayElements[i]);
Thread.sleep(5000);
}
}
If you must use a TimerTask then you could do:
public static void main(String[] args) throws InterruptedException {
String[] arrayElements = { "value1", "value2", "value3",
"value4" };
long start = System.currentTimeMillis();
for (int i = 0; i < arrayElements.length; i++) {
final String value = arrayElements[i];
new java.util.Timer().schedule(new java.util.TimerTask() {
public void run() {
System.out.println(value);
}
}, new Date(start));
start += 5000;
}
}
You put the print loop in the TimeTask.run() so when it is executed, all the value is printed out at once. What you need to do is to create a time task for each array elements. Something like:
String[] arrayElements = {"value1", "value2", "value3", "value4"};
for (final String arrayElement : arrayElements)
{
new java.util.Timer().schedule(
new java.util.TimerTask()
{
public void run()
{
System.out.println(arrayElement);
}
},
new Date(start)
);
start+=1000;
}
Hope this helps.
精彩评论