|
Previous Next
Subclass of the Thread Class
The example below is showing how to use the Thread class. There are 2 classes below. One is the XThread class (a Thread subclass). The other is the ThreadSamp that creates 3 instances of the XThread class in its main method. You should save this listing under the filename of ThreadSamp.java. This is the name of your public class and the class that contains the main method.
In our main method we create the 3 threads by sending XThread 2 values, a name we want it to use for its thread and a numerical value to use for calculation.
In our constructor for XThread we receive a String that will be sent to the method super for naming the thread. Here super will represent the constructor for the Thread class, which we are extending. The value of num1 is set from the parameter num. num1 will be different for each object created from XThread.
In the run method for the thread, we will take this object's num1 and increment it 5 times.
class XThread extends Thread {
int num1;
XThread(String threadName, int num) {
super(threadName);
num1 = num;
start();
}
public void run() {
String txt = Thread.currentThread().getName();
for (int i=0; i<5; i++) {
int num2 = num1 + i;
System.out.println(txt + " .....num2=" + num2);
}
}
}
public class ThreadSamp {
public static void main(String[] args) {
Thread thread1 = new XThread("thread1", 300);
Thread thread2 = new XThread("thread2", 1000);
Thread thread3 = new XThread("thread3", 2500);
}
}
The test below shows the 3 threads running. When each gains control of the processor, it holds it until it finishes its 5 additions.
We normally don't want a thread to monopolize the entire processor. It might not want to give up control to allow itself to be interrupted by the operating system or let you perform any other work on your computer.
After each calculation, we will put the current thread asleep so that other work can be done. The sleep method should be placed in a try..catch construct to handle exceptions.
class XThread extends Thread {
int num1;
XThread(String threadName, int num) {
super(threadName);
num1 = num;
start();
}
public void run() {
String txt = Thread.currentThread().getName();
for (int i=0; i<5; i++) {
int num2 = num1 + i;
System.out.println(txt + " .....num2=" + num2);
try {
//delay for one second
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
}
}
}
}
public class ThreadSamp {
public static void main(String[] args) {
Thread thread1 = new XThread("thread1", 300);
Thread thread2 = new XThread("thread2", 1000);
Thread thread3 = new XThread("thread3", 2500);
}
}
Now in our test run, we see how the threads are sharing the processor time, each allowing someone else a chance while it sleeps.
Previous Next
|