To program with threads you need to know how to answer these questions:
Where the Java thread support resides ?
When a tread executes, what code does it execute?
What states can a thread be in?
1- Where the Java thread support resides in:
* The java.lang.Thread class
* Certain parts of the java.lang.Object class
* Certain functionality of the Java language and runtime environment (e.g. the interface java.lang.Runnable).
And Every thread is an instance of the Thread class
2-When a tread executes, what code does it execute?
To cause a thread to execute, call its start() method. The start() method registers the thread with the thread scheduler.
What code is executed?
A thread executes the code in a public void run() method. There are two choices:
• The thread executes its own run() method
• The thread executes a run() method in some other object.
When the run() method returns, the thread dies.
The thread executes its own run method.
To do this, subclass the Thread class and override the run() method.
Example 1
public class PrintSlashThread extends Thread {
public void run() {
System.out.println("\");
}
Then, somewhere else in the program,
PrintSlashThread printSlashThread = new PrintSlashThread ();
cs.start();
The thread executes another objects's run method
use a constructor with an argument which is a reference to an object of a class containing the run() method which also implements the Runnable interface.
The Runnable interface has a single method,
public void run().
Example 2
public class PrintSlashThread implements Runnable {
public void run() {
System.out.println("\");
}
Somewhere in a program (often in the constructor)
PrintSlashThread printSlashThread = new PrintSlashThread ();
Thread tread = new Thread(printSlashThread);
tread.start();
What states can a thread be in?
3-The thread states are:
Running: the goal state of all threads
Waiting states: Waiting, Sleeping, Suspended, Blocked
Ready: not waiting for anything except the CPU
Dead: all done
Now you can do put all together and post some proposition and we will tolk about synchronization
Hope it helps.