Multi-Threading in Java - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Random Posts

Multiple tasks need to be executed simultaneously within a single application. The Java platform provides support for concurrent programming. To understand concurrent programming, you have to understand two things: process and thread

A process has a self-contained execution environment, whereas threads exist within a process. Threads are known as lightweight processes.

Note that creating a new thread requires fewer resources than creating a new process. Basically, threads share resources of the process, in which they exist.

There are two different ways to create threads:

  • 1. Extending Thread class
  • 2. Implementing Runnable interface

Inheriting Thread class

Here, we are defining a class inheriting the Thread class. The Thread class defines a method run , which does nothing. This method needs to be overwritten in our class as this method should contain the code of the thread.

A.java
public class A extends Thread { int i = 1; String name; public Thread t; public A(String name) { this.name = name; t = new Thread(this, "A thread"); System.out.println(name + "i am A const"); t.start(); } public void run() { for (; i < 10000;) { System.out.println(name + i); i += 2; } } }
Main.java
public class Main { public static void main(String[] args) { System.out.println("i am main meth"); A a1 = new A("T-A-1 :"); A a2 = new A("T-A-2 :"); A a3 = new A("T-A-3 :"); System.out.println("End of main."); } }

Implementing Runnable interface


Here, we are defining a thread by implementing the Runnable interface. Again in this class, we have to define the run method, which will contain the code of the thread.

B.java
public class B implements Runnable { int i = 0; String name; Thread t; public B(String name) { this.name = name; t = new Thread(this, "B thread"); System.out.println(name + "i am B const"); t.start(); } public void run() { for (; i < 10000;) { System.out.println(name + i); i += 2; } } }
Main.java
public class Main { public static void main(String[] args) { System.out.println("i am main meth"); B b1 = new B("T-B-1 :"); B b2 = new B("T-B-2 :"); B b3 = new B("T-B-3 :"); System.out.println("End of main."); } }

Thread join


In the above examples, you will see that the main thread is exiting before the completion of the child threads. If the main thread needs to be alive until all the threads are terminated, the threads are to be joined with the main thread as shown below.

Main.java
public class Main { public static void main(String[] args) { System.out.println("i am main meth"); A a1 = new A("T-A-1 :"); A a2 = new A("T-A-2 :"); A a3 = new A("T-A-3 :"); B b1 = new B("T-B-1 :"); try { a1.t.join(); a2.t.join(); a3.t.join(); b1.t.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("End of main."); } }


Happy Exploring!

No comments:

Post a Comment