Kevin
Kevin

Reputation: 23634

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.

Upvotes: 22

Views: 53259

Answers (8)

roottraveller
roottraveller

Reputation: 8232

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.

If someone interested can have a look in my GitHub repo

Upvotes: 13

Sajad Bahmani
Sajad Bahmani

Reputation: 17459

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.

Upvotes: 23

Steve
Steve

Reputation: 12393

I can answer the first 3 since I'm not too familiar with the threading features of Spring or Flex.

  1. A thread is an object that has its own registers and stack that can run parallel with other threads in a process (a process is a collection of threads).

  2. You write multi-threaded code for the program to be responsive to user interactions. Think of how annoying it would be if you had to wait for your browser to finish downloading a file before you can continue browsing.

  3. I gave an example in #2. Other examples are any programs with a GUI (the GUI has to always be responsive to user input while performing background tasks), or server type software such as a web server where you might have to respond to 1000 requests a minute. It would be better to have a separate thread for each of those responses.

Upvotes: 3

Faraz Shaikh
Faraz Shaikh

Reputation: 1

Ok to answer what is thread in java in simple word its a program/piece of code which works simultaneously with your normal class. A difference between a normal class and a thread is that a thread works simultaneously its works parallely along with the normal class. In more simpler terms lets see a example where i am currently in main function and requires a function to compute something . so if that function is not in a thread then the function will be evaluated first and after then i will return to main function on the other hand if it is a thread then the function will compute and main will will also compute its next instruction.

Now as to how a thread is created 1. extend thread class: extend thread class and write start() its a function call it using an object of current class and write a function namely void run() and in this function write the code which needs to be performed concurrently.

Each object of the class which extends thread is a customized thread.by default every thread is inactive and to activate or call that thread just write start() this will automatically call run which contains your code.

class MyThreads extends Thread
{
 int ch ;

 MyThreads(int p)
 {
  ch = p;
  start();//statement to activate thread and call run
 }  

 public void run()
 {
  if(ch == 1)
    functionx()
  else if(ch == 2)
    functiony();

 }

 void fx1()
 {
  //parallel running code here
 }

 void fx2()
 {
    //parallel running code here
 }

 public static void main(String args[])
 {

  MyThreads obj1 = new MyThreads(1);
  My3Threads obj2 = new MyThreads(2);

  //mains next instruction code here

 }
}
  1. you can also implement a interface namely Runnable but as this is a interface which is compatible with the current class so calling start will call the function run() which is written in interface but as to call our run() function call the start with a thread object like this Thread t=new thread(this); t.start();

Now to why do we go for thread,this is just like asking why do we go for multicore processor you get what I am saying, multi threading is used to execute task concurrently

A real time example would be a server any server ,consider the server of Gmail.So if g mail server was not written using multi threading then i could not log in without you logging out which means in the whole world only one person can login at one time you see how impractical it is.

Upvotes: 0

Ravindra babu
Ravindra babu

Reputation: 38910

Have a look oracle tutorial

  1. What is a thread?

Threads are sometimes called lightweight processes. Threads exist within a process — every process has at least one. Threads share the process's resources, including memory and open files. This makes for efficient, but potentially problematic, communication.

  1. Why do we go for threading?

    1. Multithreaded execution is an essential feature of the Java platform. Threads are independent of each other.

    2. You can parallelize your computation by breaking into multiple sub computations.

    3. You can use CPU cores of your server effectively.

    e.g.

    ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime()
                .availableProcessors());
    

    if you follow shared-nothing approach ( which is not possible always) between your threads, multi-threading application provides high throughput.

  2. A real time example over the threads.

    Think of WhatsApp kind of a chat application.

    The server should send and receive chat messages among thousands of users. A single threaded application is disaster to handle this use case.

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.

A Thread class can implement Runnable or extend Thread. Have a look at oracle tutorial page

You can execute business logic in Threads.

You can call different class methods in Threads.

Upvotes: 1

mezmo
mezmo

Reputation: 2480

Flex cannot directly communicate with Java threads, there would have to be some sort of messaging whether you use JMS or whatever, Flex via BlazeDS, GraniteDS, or LCDS can communicate with JMS. One thing to remember as well is that, at the moment anyway, Flash/Flex itself is single threaded, but highly asynchronous....some would say TOO asynchronous...so any use of Java threads to speed things up may not have as great an effect as you might hope for.

Upvotes: 2

pdbartlett
pdbartlett

Reputation: 1519

One key concept to clear up is that a thread is an OS scheduling object, which just happens to have a Java class that represents it (as, say, Window would in the UI sub-system). Threads are not themselves a type of class.

Upvotes: 2

Stephen C
Stephen C

Reputation: 718708

As far as Spring is concerned, yes you can definitely create your own threads. But it is a better idea to use the thread pool support described in Chapter 25 of the Spring Framework Manual.

However, having requests spawn threads in a Spring-based web service (or any web service for that matter) introduces resource management issues that you may want to avoid ...

Upvotes: 1

Related Questions