Threads in Java

前端 未结 9 889
野趣味
野趣味 2020-11-30 01:11

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 re
9条回答
  •  感动是毒
    2020-11-30 02:01

    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.

提交回复
热议问题