Printing different variables using Timer and TimerTask in java -
i've got small problem concerning printing sentence using timer. know procedure of extending timertask , overriding run method here can print static sentence. in case have print list of songs (from array) , list of artists (from array) in different time periods.
for example have 3 songs: first 1 has 3 minutes, second 1 has 2.5 minutes, , third 1 has 5 minutes. output should following:
song 1 artist 1 playing... (after 3 minutes) song 2 artist 2 playing... (after 2.5 minutes) song 3 artist 3 playing... (after 5 minutes) program stops.
the code have far this:
main class:
package test; import java.util.timer; public class test { public static void main(string[] args) { timer timer = new timer("printer"); for(int = 0 ; < 3 ; i++) { thread t = new thread(); int dur = t.getdurations()[i]; timer.schedule(t, 0, dur); } } } class extending timertask:
package test; import java.util.timertask; /** * * @author graphpixel */ public class thread extends timertask { string[] song_list = { "song one", "song two", "song three" }; string[] artist_list = { "artist one", "artist two", "artist three" }; int[] durations = { 2000, 1500, 2500 }; public int[] getdurations() { return durations; } public string[] getsong_list() { return song_list; } public string[] getartist_list() { return artist_list; } @override public void run() { int = 0; system.out.println(song_list[i] + " played " + artist_list[i]); i++; cancel(); } } when run program 3 sentences printed @ same time, no time difference between them
you scheduling same thread multiple times. once scheduled, on second iteration in loop, when code tries schedule again, illegalstateexception
you need create separate thread objects in loop
import java.util.timer; public class test { public static void main(string[] args) { timer timer = new timer("printer"); for(int = 0 ; < 3 ; i++) { thread t = new thread(); timer.schedule(t, 0, t.getdurations()[i]); } } }
Comments
Post a Comment