Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Threads in Java

I was today asked in an interview over the Thread concepts in Java? The Questions were...

  1. What is a thread?
  2. Why do we go for threading?
  3. A real time example over the threads.
  4. Can we create threads in Spring framework service class.
  5. Can flex call a thread?

I did not answer any questions apart from definition of Thread, that too I just learnt from internet.

Can anyone explain me clearly over this.

Update:

What is a difference between a thread and a normal java class. why do we need threading... can i execute business logic in threads. Can i call a different class methods in Threads.

like image 779
Kevin Avatar asked May 19 '10 12:05

Kevin


People also ask

What is thread in Java and types?

Java offers two types of threads: user threads and daemon threads. User threads are high-priority threads. The JVM will wait for any user thread to complete its task before terminating it. On the other hand, daemon threads are low-priority threads whose only role is to provide services to user threads.

What is thread with example?

Thread is often referred to as a lightweight process. The process can be split down into so many threads. For example, in a browser, many tabs can be viewed as threads. MS Word uses many threads - formatting text from one thread, processing input from another thread, etc.

Why do we use threads in Java?

Threads allows a program to operate more efficiently by doing multiple things at the same time. Threads can be used to perform complicated tasks in the background without interrupting the main program.

What is thread in oops?

A thread, in the context of Java, is the path followed when executing a program. It is a sequence of nested executed statements or method calls that allow multiple activities within a single process.


2 Answers

To create threads, create a new class that extends the Thread class, and instantiate that class. The extending class must override the run method and call the start method to begin execution of the thread.

Inside run, you will define the code that constitutes a new thread. It is important to understand that run can call other methods, use other classes and declare variables just like the main thread. The only difference is that run establishes the entry point for another, concurrent thread of execution within your program. This will end when run returns.

Here's an example:

public class MyThread extends Thread {
    private final String name;

    public MyThread(String name) {
        this.name = name;
    }

    public void run() {
        try {
            for (; ; ) {
                System.out.println(name);
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            System.out.println("sleep interrupted");
        }
    }

    public static void main(String[] args) {
        Thread t1 = new MyThread("First Thread");
        Thread t2 = new MyThread("Second Thread");
        t1.start();
        t2.start();
    }
}

You will see this on the screen:

First Thread
Second Thread
First Thread
Second Thread
First Thread

This tutorial also explains the Runnable interface. With Spring, you could use a thread pool.

like image 163
Sajad Bahmani Avatar answered Oct 12 '22 22:10

Sajad Bahmani


Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilisation of CPU. Each part of such program is called a thread. So,

Threads are light-weight processes within a process.

Threads can be created by using two mechanisms :

  1. Extending the Thread class
  2. Implementing the Runnable Interface

Thread creation by extending the Thread class

We create a class that extends the java.lang.Thread class. This class overrides the run() method available in the Thread class. A thread begins its life inside run() method. We create an object of our new class and call start() method to start the execution of a thread. Start() invokes the run() method on the Thread object.

class MultithreadingDemo extends Thread{
public void run()    {
    try {   // Displaying the thread that is running
        System.out.println ("Thread " + Thread.currentThread().getId() 
                                + " is running"); 
        }
        catch (Exception e){   // Throwing an exception
            System.out.println ("Exception is caught");
        }
    }
} 
public class Multithread{
    public static void main(String[] args)    {
        int n = 8; // Number of threads
        for (int i=0; i<8; i++)        {
            MultithreadingDemo object = new MultithreadingDemo();
            object.start();
        }
    }
}

Thread creation by implementing the Runnable Interface

We create a new class which implements java.lang.Runnable interface and override run() method. Then we instantiate a Thread object and call start() method on this object.

class MultithreadingDemo implements Runnable{
public void run()    {
    try   {     // Displaying the thread that is running
        System.out.println ("Thread " +  Thread.currentThread().getId() +
                            " is running");

    }
    catch (Exception e)   {     // Throwing an exception
        System.out.println ("Exception is caught");
    }
    }
} 
class Multithread{
    public static void main(String[] args)    {
        int n = 8; // Number of threads
        for (int i=0; i<8; i++)        {
            Thread object = new Thread(new MultithreadingDemo());
            object.start();
        }
    }
}

Thread Class vs Runnable Interface

  1. If we extend the Thread class, our class cannot extend any other class because Java doesn’t support multiple inheritance. But, if we implement the Runnable interface, our class can still extend other base classes.

  2. We can achieve basic functionality of a thread by extending Thread class because it provides some inbuilt methods like yield(), interrupt() etc. that are not available in Runnable interface.

like image 33
roottraveller Avatar answered Oct 13 '22 00:10

roottraveller