150 likes | 332 Vues
Java threading is an advanced feature that allows multiple activities to run simultaneously within a single process. As the first mainstream programming language to incorporate threading, Java enables developers to create responsive UIs and optimize performance on multiprocessor systems. Each Java program operates with at least one thread, known as the main thread. Threads share resources like memory and file handles, making them less insulated than separate processes. This guide explores the mechanics of Java threads, their states, priorities, and scheduling methods.
E N D
What is Thread • Threading is a facility to allow multiple activities to coexist within a single process. • Specialized form of Multitasking. • Java is the first mainstream programming language to explicitly include threading within the language itself, rather than treating threading as a facility of the underlying operating system.
What is Thread • A process can support multiple threads, which appear to execute simultaneously and asynchronously to each other • Threads are independent, concurrent paths of execution through a program. • Each Thread has • Stack • Program Counter • Local Variables
Thread Sharing • Threads within a process are less insulated from each other than separate processes are. They share memory, file handles. • Does not depend upon Operating System.
Every Java program uses threads • Every Java program has at least one thread -- the main thread. When a Java program starts, the JVM creates the main thread and calls the program's main() method within that thread.
Why use threads • Make the UI more responsive • Take advantage of multiprocessor systems • Simplify modeling • Perform asynchronous or background processing.
Thread Priority • JVM selects to run a Runnable thread with the highest priority. • All Java threads have a priority in the range 1-10. • Top priority is 10, lowest priority is 1. Normal priority by default is 5. • Thread.MIN_PRIORITY - minimum thread priority • Thread.MAX_PRIORITY - maximum thread priority • Thread.NORM_PRIORITY- maximum thread priority
Thread Scheduling • The JVM schedules using a preemptive , priority based scheduling algorithm. • All Java threads have a priority and the thread with he highest priority is scheduled to run by the JVM. • In case two threads have the same priority a FIFO ordering is followed.