Java & J2EE Page 4 - More About Multithreading in Java |
As you can see, we have arrived at the end of this sequel article. By now you should know how to work with multiple threads, create them, make them share data and variables between each other, synchronize attributes, manage their states, and make them communicate between each other. Before we finish, there are two more interesting types of classes regarding threads that we should mention. These are the Timer Class and the TimerTask Class. With the help of these we can schedule some parts of our program. Basically, the scheduled task will be run as a separate thread (like a background thread) when its appropriate time arrives. As a rule of thumb, these timer tasks should be quick, otherwise they might hog and/or speed up (since the task was delayed) the application execution. Here’s a really quick example; please complete the snippet with the required parts.
class Scheduler{ Timer timer;
public Scheduler(int seconds){ timer = new Timer(); timer.schedule(new RemindTask(), seconds*1000); }
class RemindTask extends TimerTask{ public void run(){ System.out.println(" Boo! "); // this is the actual task timer.cancel(); } } Thanks for following this series; hopefully, you’ve found it educational. We welcome and appreciate all kinds of feedback in the blog comment section below; thus, feel free to write your opinion, ask questions, and we'll clarify your dilemmas. In closing, I’d like to invite you to join our experienced community of technology professionals on all areas of IT&C starting from software and hardware up to consumer electronics at Dev Hardware Forums. Also, be sure to check out the community of our sister site at Dev Shed Forums. We are friendly and we’ll do our best to help you.
blog comments powered by Disqus |
|
|
|
|
|
|
|