A program that uses many threads needs to be subject to some set of rules to determine which thread should be running at any one time, and how to switch between threads. Without this switching around (scheduling), there's no real reason to use threads in the first place, since some threads will never have a chance to run.
Because of this, threads are given priority levels (higher priority runs before a lower priority thread).
TL;DR: Needs to be a way to flip between threads, and to prioritize them, otherwise, pointless.
There's basically 3 ways of switching threads:
a) The current thread is either blocked, or is terminated, allowing another thread to take over.
b) A higher priority thread becomes available and preempts the current thread.
c) A scheduling event occurs, forcing the current thread to suspend in favor of another thread. Known as time-slicing
And that's it! We can now move on to an example program!
A Text Clock
This example is taken like, right out of the textbook, since I don't personally know much about threads, even on the technical level which we just finished going through, let alone actual implementation, so bear with me if I screw up!
Statement of Problem
Write a drawing program that acts as a simple text clock by displaying the date and time, updated once every second.
In one of the Java packages, java.util, there's a Date class, which can give us the current date and time, so that's what we'll use.
To write this program, we need a thread that updates the clock once per second. The run method for this thread can just be a loop that waits for a second, then calls some method to re-print the date. There's a subclass of Thread named Timer that we can define as follows:
Well, I left commentary in, so the gist of this should be easy enough! The entire construct of the Timer class is 3 variables, with a constructor to set 2 of them.
Then we have 2 methods, the simpler one being a way to quickly turn off the timer, and the more complex one just holds for a second (or whatever waitTime you put in), then repaints the info on the panel, and just loops. FOREVER.
It's okay though, we have another class coming tomorrow and stuff, but that's all for now. Questions welcome! Comments, too! Follow, subscribe, share etc, on Monday!
And as part of a shameless plug for a friend, if you're interested in classic movies/books/music, visit his site here (fixed), and feel free to throw loads of criticism at us.