Threads in Java

前端 未结 9 891
野趣味
野趣味 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:11

    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.

提交回复
热议问题