Threads - The Theory

A Thread is a set of code that can be run by itself. Each thread has its own local variables. When you start a thread, it can go off and complete its tasks.

You have already been using threads - without being aware of it because threads are built into the basic running of a java program. When you ran a main method, java spawned a main thread. Java executes all of the methods in the main method. The thread died when the main method was complete. When you ran an applet, you were using at least two threads: one thread was started to listen to the actionEvents and deliver them to the actionPerformed method and another thread handled the paint method. You may have noticed that the repaint and paint methods were a little slow to respond to their calls - this is because their thread has a lower priority than the actionEvent thread.

All programs that you use, especially the Operating System use threads. They are the basis of something that is called concurrent programming. When you start a new program (say Word or Excel), a new thread is started to handle the actions of that program.

In java, there are some key pieces of code involved in running a thread:

implements Runnable added to the class declaration line
public void run() the method needed in every thread class
myThread.start() the way you start the run method in your Thread class.
try{ Thread.sleep(1000);} catch(InterruptedException e){} the code that goes in your run method to make it wait awhile before you move on.

Implement or Extends?

Questions

  1. Look up java.lang.Runnable in the help file. What methods does it have?
  2. Look up java.lang.Thread in the help file. What methods does it have?