Threads Deep Dive

Multithreading

  • Multithreading in Java is a process of executing multiple threads simultaneously.

  • A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking.

  • However, we use multithreading than multiprocessing because threads use a shared memory area.

  • They don’t allocate separate memory area so saves memory, and context-switching between the threads takes less time than process.

  • Java Multithreading is mostly used in games, animation, etc.

Advantages of multithreading

  • It doesn’t block the user because threads are independent and you can perform multiple operations at the same time.

  • You can perform many operations together, so it saves time.

  • Threads are independent, so it doesn’t affect other threads if an exception occurs in a single thread.

Multitasking

Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU. Multitasking can be achieved in two ways:

  • Process-based Multitasking (Multiprocessing)

  • Thread-based Multitasking (Multithreading)

Process-based Multitasking (Multiprocessing)

  • Each process has an address in memory.

  • In other words, each process allocates a separate memory area.

  • A process is heavyweight.

  • Cost of communication between the process is high.

  • Switching from one process to another requires some time for saving and loading registers, memory maps, updating lists, etc.

Thread-based Multitasking (Multithreading)

  • Threads share the same address space.

  • A thread is lightweight.

  • Cost of communication between the thread is low.

Methods in thread class

MethodDescription
public void run()is used to perform action for a thread.
public void start()starts the execution of the thread.JVM calls the run() method on the thread.
public void sleep(long miliseconds)Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.
public void join()waits for a thread to die.
public void join(long miliseconds)waits for a thread to die for the specified miliseconds.
public int getPriority()returns the priority of the thread.
public int setPriority(int priority):changes the priority of the thread.
public String getName()returns the name of the thread.
public void setName(String name)changes the name of the thread.
public Thread currentThread()returns the reference of currently executing thread.
public int getId()returns the id of the thread.
public Thread.State getState()returns the state of the thread.
public boolean isAlive()tests if the thread is alive.
public void yield()causes the currently executing thread object to temporarily pause and allow other threads to execute.
public void suspend()is used to suspend the thread(depricated).
public void resume()is used to resume the suspended thread(depricated).
public void stop()is used to stop the thread(depricated).
public boolean isDaemon()tests if the thread is a daemon thread.
public void setDaemon(boolean b)marks the thread as daemon or user thread.
public void interrupt()interrupts the thread.
public boolean isInterrupted()tests if the thread has been interrupted.

Starting a thread

The start() method of Thread class is used to start a newly created thread. It performs the following tasks:

  • A new thread starts(with new callstack).

  • The thread moves from New state to the Runnable state.

  • When the thread gets a chance to execute, its target run() method will run.

Java Thread Example by extending Thread class

class Multi extends Thread {
    public static void main(String args[]) {
        Multi t1 = new Multi();
        t1.start();
    }

    public void run() {
        System.out.println("thread is running...");
    }
}  

Output:

thread is running...

Java Thread Example by implementing Runnable interface

class Multi3 implements Runnable {
    public static void main(String args[]) {
        Multi3 m1 = new Multi3();
        Thread t1 = new Thread(m1);   // Using the constructor Thread(Runnable r)
        t1.start();
    }

    public void run() {
        System.out.println("thread is running...");
    }
}

Output:

thread is running...

Using the Thread Class: Thread(String Name)

We can directly use the Thread class to spawn new threads using the constructors defined above.

class MyThread1 {
    // Main method
    public static void main(String argvs[]) {
// creating an object of the Thread class using the constructor Thread(String name)   
        Thread t = new Thread("My first thread");

// the start() method moves the thread to the active state  
        t.start();
// getting the thread name by invoking the getName() method  
        String str = t.getName();
        System.out.println(str);
    }
}  

Output:

My first thread

Using the Thread Class: Thread(Runnable r, String name)

class MyThread2 implements Runnable {
    // main method
    public static void main(String argvs[]) {
// creating an object of the class MyThread2
        Runnable r1 = new MyThread2();

// creating an object of the class Thread using Thread(Runnable r, String name)
        Thread th1 = new Thread(r1, "My new thread");

// the start() method moves the thread to the active state
        th1.start();

// getting the thread name by invoking the getName() method
        String str = th1.getName();
        System.out.println(str);
    }

    public void run() {
        System.out.println("Now the thread is running ...");
    }
}    

Output:

My new thread
Now the thread is running ...
core java threads programming multithreading concurrency

Subscribe For More Content