Threads Basics in Java

A thread is independent and isolated path of execution in single program. Many threads can run concurrently either synchronously or asynchronously with in a single program. Every thread in Java is controlled using Java.lang.Thread class.

Check out the YouTube videos of Threads in Java below:



Some properties of Threads are :

1. Threads are lightweight processes.
2. Context switching between threads is less expensive.
3. Cost of intercommunication between threads is relatively low.

How to create Threads?

1. By extending the Thread class (java.lang.Thread)
2. Implement the Runnable Interface (java.lang.Runnable)

Lets see the First method of creating threads by extending the Thread class

Code snippet:


public class AppWindows extends Thread {
       Private String data;
       Public AppWindows(String data){
       this.data = data;
    }
       public void run() {
            AppWindowsHelper appwindowsHelper =  new AppWindowsHelper();
            appWindowsHelper.status(this.data);
        }
    }

This is often consider as Bad practice because usually we extend superclass to create subclass with more advanced features but here we are just overriding the run () method and not doing anything else, but threads have more advanced methods.

The other method is to implement the Runnable interface which is generally recommended.

Code snippet:


public class AppWindows implements Runnable {

        public void run() {
            for (int i = 1; i < 10; i++) {
                System.out.println("Currently the thread" + " " + Thread.currentThread().getName() + " " + "is running");
               
            }

        }
    }

Below is the program where Junit is running two threads to run two test cases concurrently.


public class JunitTestHelper {

        public static void main(String[] args)
        {
            JunitTest junitTest = new JunitTest();
            Thread testOneThread = new Thread(junitTest, "TestCase1");
            Thread testTwoThread = new Thread(junitTest, "Testcase2");
            testOneThread.start();
            testTwoThread.start();
        }
    }


public class JunitTest implements Runnable {

        public void run() {
            for (int i = 1; i < 10; i++) {
                System.out.println("Currently the thread" + " " + Thread.currentThread().getName() + " " + "is running");
               
            }

        }
    }


Comments

Popular posts from this blog

Tricky Questions or Puzzles in C

Program to uncompress a string ie a2b3c4 to aabbbcccc

Number series arrangement puzzles