Threads
A thread
(API) is a process running independently.See Tutorial Thread
A java program uses threads to perform several tasks (loading images,
sounds, playing sounds et c.). The programmer can control the threads by
creating, starting and stopping threads. A thread contains the run method
which defines the function of the thread.
A thread can have a priority which determines how the system runs the
threads. The higher the priority the more "service" the thread will get.
A simple thread demonstrates the independence of threads. (See A Simple
Thread Example in tutorial) Two similar threads print lines on screen.
Random delays are used between line prints.
A more advanced - yet simple - example demonstrates how threads can
be used to create independent movement on screen. (See Thread Attributes/Thread
Priority - page in Tutorial)
We use three threads here
-
Runner 1 - moves one line (from 1 to 40 000)
-
Runner 2 - moves one line (from 1 to 40 000)
-
Drawing thread: Draws the image (with Runner 1 and Runner2) then sleeps
letting runner 1 and runner 2 advance) then gets contol again until finished.
The turns are determined by priorities. The drawer has highest priority.
It slleps to let others run. If it would not sleep others would have no
chance to run (depending on the operating system).