Object Oriented Software Engineering   View all facts   Glossary   Help
subject > thread > thread in Java
Upthread

thread in Java
subjectfact 
thread in Javahas example
public class ThreadExample implements Runnable
{
private int counterNumber; // Identifies the thread
private int counter; // How far the thread has executed
private int limit; // Where counter will stop
private long delay; // Pause in execution of thread in milisecs

// Constructor
private ThreadExample(int countTo, int number, long delay)
{
counter = 0;
limit = countTo;
counterNumber = number;
this.delay = delay;
}

//The run method; when this finishes, the thread terminates
public void run()
{
try
{
while (counter <= limit)
{
System.out.println("Counter "
+ counterNumber + " is now at " + counter++);
Thread.sleep(delay);
}
}
catch(InterruptedException e) {}
}

// The main method: Executed when the program is started
public static void main(String[] args)

//Create 3 threads and run them
Thread firstThread = new Thread(new ThreadExample(5, 1, 66));
Thread secondThread = new Thread(new ThreadExample(5, 2, 45));
Thread thirdThread = new Thread(new ThreadExample(5, 3, 80));

firstThread.start();
secondThread.start();
thirdThread.start();
}
}
link: chapter2section2.8.html#1061, 2001-08-30 14:58:01.0
is a subtopic of The Basics of Java2001-08-30 14:58:02.0
is created by
  1. Creating a class to contain the code that will control the thread. This can be made a subclass of Thread class, or else it can implement the interface Runnable.
  2. Writing a method called run in your class. The run method will normally take a reasonably long time to execute - perhaps it waits for input in a loop. When the thread is started, this run method executes, concurrently with any other thread in the system. When the run method ends, the thread terminates
  3. Creating an instance of Thread class, or your subclass of Thread class, and invoking the start operation on this instance. If you implemented the interface Runnable, you have to pass an instance of your class to the constructor of Thread class.
link: chapter2section2.8.html#1037, 2001-08-30 14:58:02.0
is a kind of thread2001-08-30 14:58:02.0
threadcan run at the same time as another thread2001-08-30 14:58:01.0
is supported by many operating systems and programming languages2001-08-30 14:58:01.0
see also Thread class2001-08-30 14:58:01.0
see also thread in Java2001-08-30 14:58:01.0