Turn Desktop View Off
by Dinesh Thakur

When more than one thread has to use a shared resource, Java finds a way of ensuring that only one thread uses the resources at one point of time; this is called synchronization.



 
by Dinesh Thakur

A thread is always in one of five states: newborn, runnable, running, dead and blocked. Figure shows the life-cycle of a thread.

 
by Dinesh Thakur

In Java, threads are objects and can be created in two ways:

1. by extending the class Thread

2. by implementing the interface Runnable



 
 
 
by Dinesh Thakur
 
by Dinesh Thakur

Multithreading replaces event loop programming by dividing the tasks into discrete and logical units. Threads also helps in avoiding polling. Polling is usually implemented by a loop that is used to check some condition repeatedly. Once the condition is true, appropriate action is taken, this results in wastage of CPU time. Suppose that the producer has to wait until the consumer is finished before it generates more data. In a polling system, the consumer would waste many CPU cycles while it waits for the producer to produce. Once the producer has finished, it would start polling, wasting more CPU cycles waiting for the consumer to finish, and so on.



 
by Dinesh Thakur

Since multiple threads run independently without any communication between them, some problems may arise because of this asynchronous behavior of threads. Sometimes, we need an operation to be performed by only one thread at a time. Performing the same task by two threads simultaneously may lead to inconsistent results. So to ensure that two thread don't execute the conflicting operations together and to initiate communication among thread, a process called synchronization is used.

 
by Dinesh Thakur

Thread priorities are used by the thread scheduler to decide when each thread should be allowed to run. Higher priority threads get more CPU time than lower priority threads. A higher-priority thread can also preempt a lower-priority one. For instance, when a lower-priority thread is running and a higher-priority thread resumes (from sleeping or waiting on I/O, for example), it will preempt the lower priority thread.



 
 
by Dinesh Thakur

To determine whether a thread has finished. we can call isAlive() on the thread. This method is defined by Thread and its syntax is :

final boolean isAlive()

This method returns true if the thread upon which it is called is still running otherwise it returns false.

 
by Dinesh Thakur

We first make a class MultipleThreads which extends Thread class and then we create an instance of that class t1 and pass the string "Child Thread" as parameter to it which assigns the name of the thread as Child Thread and also displays the information of the child thread on the screen. After that the start() method is invoked on that object which initiates the run() method. Before executing run() method of MultipleThreads, control returns to main(). In main() method, the for loop is executed which is supposed to print Mainthread : 1



 
by Dinesh Thakur

Another method to create a thread is to create a class that implements the Runnable interface. Runnable abstracts a unit of executable code. We can construct a thread on any object that implements Runnable. To implement Runnable, a class need only implement a single method called run().

 
by Dinesh Thakur

One way to create a thread is to create a new class that extends Thread, and then to create an instance of that class. The extending class must override the run() method, which is the entry point for the new thread. It must also call start() to begin execution of the new thread.

 
by Dinesh Thakur

In this Java Example, a reference to the current thread (the main thread) is obtained by calling currentThread(), and this reference is stored in a local variable t. Then, we display the information about the thread. After that, a loop counts from 0 to 10, pausing one second between each line. The pause is accomplished by the sleep() method. The argument to sleep() specifies the delay period in milliseconds. The sleep() method might throw an InterruptedException if some other thread interrupts the sleeping one.



 
by Dinesh Thakur

Java has two types of threads : user thread and daemon thread.

A user thread is a thread that will run on its own independently of other threads. In other words, a user thread has life of its own that is not dependent on the thread that creates it. It can continue execution, even after the end of the thread that created it. One example of user thread is the main thread which runs your main () thread. On the other hand, a daemon thread is subordinate to a user thread i.e. a daemon thread will automatically terminate when no more user threads are running in the application.



 
by Dinesh Thakur

Every thread in Java has a priority that helps the thread scheduler to determine the order in which threads are scheduled. The threads with higher priority will usually run before and/or more frequently than lower priority threads. By default, all the threads had the same priority i.e. they are regarded as being equally important by the scheduler, when a thread is created it inherits its priority from the thread that created it. However, you can explicitly set a thread's priority at any time after its creation by calling its setPriority () method. This method accepts an argument of type in t that defines the new priority of the thread. Its



 
by Dinesh Thakur

When a large number of threads are created, degrades the performance of your application. So Java provides a technique of thread pooling to solve this problem.

The thread pooling allows you to reuse a single thread repeatedly instead of creating a new thread for each task and allowing it to be destroyed when the task completes. It avoids the overhead associated with creating a new thread by maintaining a pool of available threads and retrieving one from the pool when necessary.



 
by Dinesh Thakur

In order to apply locks explicitly, an instance of the Lock interface needs to be created which is defined in the java.util.concurrent. Locks package. Using the Lock interface is similar to using the synchronized keyword. The Lock interface provides lock () and unlock () methods to acquire and release the lock respectively.



 
by Dinesh Thakur

Method level synchronization prevents two threads from executing method on an object at the same time. A method can be synchronized by using the synchronized keyword as a modifier in the method declaration. Its syntax is a follows,

 
by Dinesh Thakur

final void join () - The isAlive () method occasionally useful as continuously checking the value returned by this method and then sleeping makes a very inefficient use of the CPU time. So a better alternative to wait for a thread to die is to use join () method of the Thread class.



 
by Dinesh Thakur

In order to make sure that the main thread finishes last, we introduced a long enough delay by calling the sleep () method within the main() method so that all other threads finish before the main thread. But this of course is hardly a satisfactory solution because if your estimate for the time delay is too short then other threads could finish after the main thread finishes. Therefore, the Thread class provide method isAli ve ()  to determine if a thread has ended .

 
by Dinesh Thakur

Another way to create a thread in Java is to define a class that implements Runnable interface. The previous technique of creating threads by extending the Thread class does not workwhen you want a class that extends another class and can also be run as a thread. This is becauseJava supports only single inheritance i.e. does not allow a class to extend more than one class. So insuch a case implement the Runnable interface. The Runnable interface declares only one method run () that contains the code that will be executed when the thread is started. Therefore, if youdefine a class that implements the Runnable interface then it must implement the run () method.



 
by Dinesh Thakur

In this Example, we shows how the constructors and methods of the Thread class are used. Here, we have created a subclass MyThread that extends Thread class. This class consists of a field which stores the time in milliseconds for which the thread will sleep. It also contains a parameterized constructor that contains two parameters str of String type and d of int type. This constructor calls the superclass constructor that sets the Thread's name to the value passed in str and delay field is set to value passed in d.

 
by Dinesh Thakur

This single sequence of executable statements within a program is known as a thread. In other words, a thread is s flow of execution of a task in a program so it known as a thread of execution or a thread of control.

 
by Dinesh Thakur

Thread is a lightweight process. It is lightweight because they utilize the minimum resources of the system. Thread is an independent concurrent path of execution of a group of statements. Thread takes less memory and less process time.



 
by Dinesh Thakur

If we talk about the mechanism of synchronization, then as one thread exits from the monitor then it must inform the waiting threads that it has left the monitor, now suspended thread can proceed to acquire the lock on the resources or entered in the monitor. If that is not possible then the waiting thread will always be in the waiting list. So, to solve this problem threads must communicate with each other.

 
by Dinesh Thakur

When two or more threads wants to access a shared resource, then it must ensure that the resource will be used by only one thread at an instant of time. The mechanism of this process is called synchronization. Synchronization is the concept of the monitor or semaphore. Monitor works as mutex and restrict to one thread to own a monitor at a given time. As the thread acquires the lock, all the threads that want to acquire the monitor will be suspended. As the first thread exits from the monitor, one thread will acquire monitor from the waiting list of threads.

 
by Dinesh Thakur

 Priority allow the scheduler to take the decision when the thread should be allowed to run, and in which order. The higher priority threads get more CPU time then lower priority threads. A lower priority thread can be preempted by higher priority thread. The threads having equal priority get equal CPU time.



 
by Dinesh Thakur

Multithreading is a powerful programming tool that makes it possible to achieve concurrent execution of multiple units of a program. Each portion of a program-designated a thread-may execute concurrently with others. Multithreading basically enables a program to do more than one task at a time and also to synchronize these tasks. Java builds thread support directly into the language. Multithreading support for Java includes thread creation, thread prioritizing, thread scheduling, resource locking (thread synchronization) and establishing inter-thread communication.



 
by Dinesh Thakur

By implementing the Runnable interface the thread creation is the easiest way. You can construct a thread on any type of object that implements Runnable. To implement Runnable interface, a new class need only to implement run() method. When you implement the Runnable interface then create an instance of Thread from within that class. The Thread class has several constructor.

 
by Dinesh Thakur

In Java, a user defined thread can be created to implement the Runnable interface. The Runnable interface has only one method run() that you must have to implement in your class, that you want to create as thread. The run() is the method in which that code is written, which is counted as thread task.



 
by Dinesh Thakur

As any Java program comes under execution, first thread starts immediately, called the main thread. There are two importance's of main thread as follows:



 
by Dinesh Thakur

The Java language and its run-time system was designed keeping in mind about multithreading. The run-time system depend upon multithreading. Java provides asynchronous thread environment, this helps to increase the utilization of CPU.