Java & J2EE Page 3 - The Basics of Multiple Threads in Java |
On the previous page we learned the first solution to multi-threading; it covered extending the Thread class. The Java programming language does not allow multiple inheritances. This is the major pitfall of this solution. With HTML apps, it is mandatory to extend the Applet class, thus the one and only allowed inheritance is already consumed. So this would mean no chance whatsoever for multi-threading. This is why the other solution, which implements the Runnable interface, was designed. The Runnable interface defines only one method, and that's the run() method. Once again we need to code this method when implementing the Runnable interface. Right after, in order to create multiple threads, we first need to create Runnable object instances, and then we're going to pass-by-value the objects to the Thread constructor. Check out the example below. class MyRunnable implements Runnable{ private int a;
public MyRunnable(int a){ this.a = a; }
public void run(){ for (int i = 1; i <= a; ++i){ System.out.println(Thread.currentThread().getName() + " is " + i); try{ Thread.sleep(1000); } catch (InterruptedException e){} } } }
class MainMyThread{ public static void main(String args[]){ MyRunnable thr1, thr2; thr1 = new MyRunnable(5); thr2 = new MyRunnable(10); Thread t1 = new Thread(thr1); Thread t2 = new Thread(thr2); t1.start(); t2.start(); } } The output will be the same as earlier. Thread-0 is 1 Thread-1 is 1 Thread-0 is 2 Thread-1 is 2 Thread-0 is 3 Thread-1 is 3 Thread-0 is 4 Thread-1 is 4 Thread-0 is 5 Thread-1 is 5 Thread-1 is 6 Thread-1 is 7 Thread-1 is 8 Thread-1 is 9 Thread-1 is 10 All right, so this second solution to creating new threads by implementing the Runnable interface is the optimal way to do this when multiple inheritances are required. The earlier solution is a bit easier to use since it doesn't require that much work. With the Runnable interface implementation we need to declare Thread objects, initialize the Runnable object instances, and call the Thread's constructor on them. Until now we've learned that both solutions execute a thread using the start() method. This is critical! Lots of beginners fall into the trap of explicitly calling the run() method of a thread object. This is wrong-it won't execute the thread as a new one; instead, everything will be processed via the conventional solo-thread approach. Therefore, the proper way is to always start a thread using the start() method. At its end, this creates the new thread and right after calls the run() method, just like any other method, but in that newly- created thread. This is the key. Always be careful.
blog comments powered by Disqus |
|
|
|
|
|
|
|