Saturday, October 17, 2015

Multi Thread programming

There are two ways for multi thread programming: one is extending Thread class, and the other is implementing Runnable interface. I will show you the second way here; implementing Runnable interface. I used this way in this post.

To do the multi thread programming, you must do the following things:

1, Create a class which implements Runnable interface.
2, Implement run methond inside the class.
3, Create an object of the class.
4, Create an object of Thread class with a constructor of which the argument is the object (which we have created in 3.)
5, Use the start method of the object of the Thread class.

public class Test1 implements Runnable { public void run() { for (int i = 0; i <= 10 ; i++) { System.out.println(i + "Hello, world!"); } } public static void main(String[] args) { Test1 test1 = new Test1(); Test1 test2 = new Test1(); Thread t1 = new Thread(test1); Thread t2 = new Thread(test2); t1.start(); t2.start(); } }

Result. You can see there are two threads.

Further reading
What is a thread? - Web based programming tutorials
http://www.webbasedprogramming.com/Java-Unleashed-Second-Edition/ch9.htm