Threads in Java

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

    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-30 02:13

    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 ...

    0 讨论(0)
提交回复
热议问题