Sunday, January 23, 2011

FAQS on threads concept on JAVA

         Answer: Threaded programming is normally used when a program is required to do more than one task at the same time. Threading is often used in applications with graphical user interfaces; a new thread may be created to do some processor-intensive work while the main thread keeps the interface responsive to human interaction.
The Java programming language has threaded programming facilities built in, so it is relatively easy to create threaded programs. However, multi-threaded programs introduce a degree of complexity that is not justified for most simple command line applications. 

Question: What is a thread?

Answer: In Java the Thread class represents a single independent path of execution in a Java Virtual Machine. When you run a Java program it implicitly starts a single thread of execution. The Thread class enables programmers to create additional threads and set them running. A number of threads may run in parallel, but only one is actively executed at a given moment.
The Java runtime system uses fairly complex thread scheduling mechanisms to coordinate the execution of threads, but this does not require privileged knowledge or detail level intervention by programmers. Programmers can manage the high level creation, initiation and distribution of tasks amongst threads through simple Application Programming Interface (API) methods.
The example below shows the simplest approach to thread creation and task execution; construct a new Thread with a Runnable argument and start it.

Question: How do Java threads make the environment asynchronous?

Answer: The thread mechanism in Java begins with the main entry point thread the runtime environment creates to start a Java program. When you use that initial thread create secondary threads, each one runs independently of the other. The Java virtual machine manages the execution of the threads so they behave as if they all run at the same time, in fact each thread briefly takes turns at execution.
In its simplest form there may be no communication or synchronization between multiple threads in a Java program and they each run to completion independently of each other. In this respect Java threads are fundamentally asynchronous, there is no master clock that governs when threads will run and when they synchronize variables to “catch-up” with each other.
        It is often necessary and more useful if threads do check ready states before progressing, synchronize read and write access to shared variables and call-back to each other when their work is done. This is where the synchronized keyword and the various sleep(), wait() and notify() methods are used to more closely schedule the interaction between asynchronous threads.

No comments:

Post a Comment