Multithreaded Application Example

In Java application, PrintNumbersThread, which includes thread code that simply lists the numbers 1 to 10. The application will have two thread instances; the thread will append the thread instance name to the output number so that we can distinguish between the instances. Finally, we will use the sleep method within the thread's run method to cease execution every half- second so that we can interleave the two thread instances' output.

PrintNumbersThread

public class PrintNumbersThread extends Thread
{
String name;

public PrintNumbersThread(String threadName)
{
name = threadName;
}

public void run()
{
int i;

for (i=1; i<11; i++)
{
System.out.println(name + '': " + i);
try
{
Thread.sleep(500);
}
Catch(InterruptedException e){}

}
}
}


Line 1 indicates that PrintNumbersThread is a Thread subclass. The PrintNumbersThread class contains a constructor (lines 4–6) that simply assigns the supplied thread's instance name to the variable name. The run method (lines 8–17) contains a for loop that is executed ten times. Within the for loop (line 12), we print the thread instance's name followed by the numbers 1 to 10. In line 14, we use the sleep method to cease the current thread's execution for 500 milliseconds. This will enable any other started threads to resume execution. To use the sleep method, we must enclose the sleep statement within a try catch statement that handles an InterruptedException. Failure to do so will cause the program's compilation to fail.

The RunThreads application invokes PrintNumbersThread.


RunThreads

public class RunThreads
{

public static void main(String args[])
{
PrintNumbersThread thread1;
PrintNumbersThread thread2;
thread1 = new PrintNumbersThread(“Thread1”);

thread2 = new PrintNumbersThread(“Thread2”);

thread1.start();
thread2.start();
}
}



In lines 7–8, we create two instances of the thread, thread1 and thread2, by invoking the PrintNumbersThread constructor. In lines 9–10, we use the
java.lang.Thread.start method to start the two thread instances.

The output of RunThreads is as follows:

> java RunThreads
Thread1: 1
Thread2: 1
Thread1: 2
Thread2: 2
Thread1: 3
Thread2: 3
Thread1: 4
Thread2: 4
Thread1: 5
Thread2: 5
Thread1: 6
Thread2: 6
Thread1: 7
Thread2: 7
Thread1: 8

Thread2: 8
Thread1: 9
Thread2: 9
Thread1: 10
Thread2: 10

No comments:

Post a Comment