Monday 15 June 2015

Part 1. Thread in Java - Creation of thread

Thread in Java

What is process, thread, its benefits?
A process is an execution unit on an operating system. Each process running on OS has at least one thread. So the thread is a smaller unit of execution. A process may contains many threads, it is called multiple threaded program. These threads can be executed at any particular time. Normally, when programmer writes a program, they usually write a sequential tasks, for instance, after data_1 is created by task one, then task two accepts data_1, these tasks run in sequential way. With multiple threads, the program can execute them simultaneously.
It can be seen that it brings much advantages from its features. For example, program contains many threads will be executed much more faster than that of program has only one thread.
In Java, every application has a thread named “main thread”, it is created newly by JVM at program start-up.
Two ways to create threads
There are two ways to create Thread in Java:
  1. Implementing Runnable interface
  2. Extending Thread class
Note that, we have to add the execution codes in the run() method.
Two classes below demonstrate how to create two threads which print numbers simultaneously.
package threads;

public class PrintNumber_1 implements Runnable{
int x = 20;
public PrintNumber_1(int x) {
this.x = x;
}
@Override
public void run() {
for(int i=0; ii++){
System.out.println("I'm : " + i+", of "+this.getClass().getName());
try {
Thread.sleep(500);//Sleeping in 0.5 second
} catch (InterruptedException e) {
}
}
}
}
package threads;

public class PrintNumber_2 extends Thread {
int x;
public PrintNumber_2(int x) {
this.x = x;
}
@Override
public void run() {
for (int i = 0; i < x; i++) {
System.out.println("I'm : " + i + ", of "
+ this.getClass().getName());
try {
Thread.sleep(500);// Sleeping in 0.5 second
} catch (InterruptedException e) {
}
}
}
}
public class ThreadDemo {
public static void main(String[] args){
int count=10;
PrintNumber_1 pn1 = new PrintNumber_1(count);
Thread tpn = new Thread(pn1);
tpn.start();
System.out.println("PrintNumber_1 thread is started....");
PrintNumber_2 pn2 = new PrintNumber_2(count);
pn2.start();
System.out.println("PrintNumber_2 thread is started....");
}
}
The output:
PrintNumber_1 thread is started....
PrintNumber_2 thread is started....
I'm : 0, of threads.PrintNumber_1
I'm : 0, of threads.PrintNumber_2
I'm : 1, of threads.PrintNumber_1
I'm : 1, of threads.PrintNumber_2
I'm : 2, of threads.PrintNumber_1
I'm : 2, of threads.PrintNumber_2
I'm : 3, of threads.PrintNumber_1
I'm : 3, of threads.PrintNumber_2
I'm : 4, of threads.PrintNumber_1
I'm : 4, of threads.PrintNumber_2
We can see that, the main thread is finished after PrintNumber_2 thread is started..... Two printer threads are concurrency running.

Thanks for reading

No comments:

Post a Comment