Like creation of a single thread, You can also create more than one thread (multithreads) in a program using class Thread or implementing interface Runnable.
Creation of MultiThreads
Like creation of a single thread, You can also create more than one thread (multithreads) in a program using class Thread or implementing interface Runnable.
Lets see an example having the implementation of the multithreads by extending Thread Class:
class MyThread extends Thread{
|
Output of the Program
C:\nisha>javac MultiThread1.java C:\nisha>java MultiThread1 Thread Name :main Thread Name :My Thread 1 Thread Name :My Thread 2 Thread Name :My Thread 1 Thread Name :My Thread 2 Thread Name :My Thread 1 Thread Name :My Thread 2 Thread Name :My Thread 1 Thread Name :My Thread 2 Thread Name :My Thread 1 Thread Name :My Thread 2 |
In this program, two threads are created along with the "main" thread. The currentThread() method of the Thread class returns a reference to the currently executing thread and the getName( ) method returns the name of the thread. The sleep( ) method pauses execution of the current thread for 1000 milliseconds(1 second) and switches to the another threads to execute it. At the time of execution of the program, both threads are registered with the thread scheduler and the CPU scheduler executes them one by one.
Now, lets create the same program implenting the Runnable interface:
class MyThread1 implements Runnable{
|
Output of the program:
C:\nisha>javac RunnableThread1.java C:\nisha>java RunnableThread1 Thread Name :main Thread Name :My Thread 1 Thread Name :My Thread 2 Thread Name :My Thread 1 Thread Name :My Thread 2 Thread Name :My Thread 2 Thread Name :My Thread 1 Thread Name :My Thread 2 Thread Name :My Thread 1 Thread Name :My Thread 2 Thread Name :My Thread 1 |
Note that, this program gives the same output as the output of the previous example. It means, you can use either class Thread or interface Runnable to implement thread in your program.