Java Thread: multiple threading, implement Runnable and java Synchronization

Java thread

Java thread:

java thread is a piece of code within the process is called a thread. There is at least one thread within a process.

Parallel programming:

Programming with java threads is called parallel programming it means more than one task are running parallel. As we know cpu process a process only one at a time but java threading is a technique we use for parallel processing. This is not the case of parallel but in such a manner we arrange java threads that they look that multiple java threads are running parallel.

Where java threading is used:

Mostly in animation graphics and such other cases e.g. taking an example of a typing tutor. Multiple java threads are used in typing tutor. We now consider only two java threads. One thread is used to move the alphabet from top to down in the screen and another java thread is used for typing moving of text while the second process takes the same time uses giving inputs but one performed parallel. To understand more about  thread we have to first differentiate between java thread and a process.



Difference between Process and a Java thread:

The execution of a program is called process and a process may contain a set of instructions but java thread is a single sequence stream within a process. Sometimes  thread is also called a lightweight process. A process must have at least one thread or may more than one thread.

Similarities between java thread and a process:

Similarities

  • Share cpu
  • Sequential execution
  • Create child
  • If one java thread is blocked then the next will be start to run like a process.

Dissimilarities:

  • Java threads are not independent like process.
  • Every process has its own data memory location but all related java threads can share the same memory.

Some definition of Java thread:

  • Collection of thread become process.
  • Each process has at least one java thread in fact a thread is also a kind of process thread can not exist by itself a process start a thread, a process may start multiple threads.
  • A processor executes threads not process so each application has at least one process and a process always has at least one thread known as primary java thread.

Concept of Java thread:

Think of a process is a set of tasks but the problem arises when two or more tasks is to be performed concurrently as without multiple java threading concepts. The process is consists of one thread so in such a situation more than one task cannot be performed without multiple java threading concepts. So java thread is useful in such kind of situations.

Example:

Take an editor program nothing more than a process think this editor is a process this editing process contains many tasks like typing editing saving printing etc. suppose if process saves only when you stop typing and also it could not print while you type in short only one task is performed at a time. so if contain multiple java threads then you can perform multiple tasks at a time.

The main java thread:

As we have discussed above that every program has at least one thread, similarly, when a java program starts up, one thread begins running immediately this is usually called the main java thread of our program. It is the  thread from which other “child” threads is created.

Note: main java thread will be executed first we will see in the example that how the main java thread creates or start a child thread.

Now we see the main thread i.e. the information about the main thread so this java thread is created automatically when a java program starts. Now we control it manually by using an object of class thread. Through this, we obtain the information about a current thread by calling a static method currentThread(), in this case, current  thread is main.


Example: how to control the main java thread

Java thread

Programming explanation:

In above program, we did not do nothing just displaying information about the main thread and then change the name of the tread. Here we didn’t create any java thread, a java thread which is main automatically created.

We created an object t of  class Thread.

Then we called a static method (“currentThread()” through class Thread.

Then we assigned the reference about current thread to the object t.

Then we displayed the contents present in t.

Then we changed the name of a thread by call a method setName(“string”);

t.setName(“name”);

how to create java thread:

to create our own java thread there are  basically two ways to create a java thread;

  • Implement the Runnable interface.
  • Extent the java thread class.

Implementing Runnable:

The general syntax of implementing Runnable

Public class Test implements Runnable

{

Thread t;

Public void run()

{

Code for thread;

}

}

Here run() is an abstract method declared in Runnable interface and is being implemented. The code that we want it as a thread we put this code in run() method.

Extend the Java thread class:

General syntax of Extend thread class is:

Public class Test extends Thread

{

Public void run()

{

Code ;

}

}

Here we just extend a class thread, so that our class one aware of its definition. In previous we said run() is an abstract method declared in Runnable interface then only those classes can implement run() method who implements it.

A Question raised how we using run() method as we have not implement any Runnable interface?

The answer is simple as we extend the class thread which already implements the Runnable interface.


implementing runnable:

1st we look that how main thread call other java thread, which must be written in run() method.

steps in creating a java thread

1st we create an object of class thread

e.g thread t;

then we instantiate this object with new operator.

e.g t=new thread()

then thread will not slot in work until you call it method start();

e.g t.start();

this method immediately calls the run method.

Programming example: how to create threads in Java programming using implements Runnable:

output:

Java thread

in above output:   sleep (1000)     //1 sec

sleep (500)         //half sec

as we have told, main thread will always execute first.

main thread execute first i.e main thread : 0

then it sleep for 1 second.

in this 1second child thread become active and executes two times i.e half sec + half sec

i.e  child thread: 0

child thread: 1

As one second completes, the main thread again active and executes and then again sleep for 1 second.

this process goes on as the above output.

t= new thread (this);

here this means a call to the constructor of that class i.e thread class as I think there is no complexity in above program and it will clear.



extend the java thread class:

we see the example to understand about 2nd method.

Programming example: how to create threads in Java programming using extends:

Java thread

the output of above program is same as previous one. the only difference is in coding, we made a little difference just extends the class thread. notice that call to super () inside createthread () constructor, this invokes the following form of the java thread constructor.

public thread (string thread Name)

here java thread name specifies the name of the thread.

Here there are two approaches to create java threads, but I prefer it to use implement Runnable interface, it depends on you which approach you use, but I prefer first one.

Creating Multiple java threads:

in previous examples we have created only one thread i.e there are total two java threads one is main thread which is created automatically and 2nd one is the child thread created our own, So we can also create many child threads as needs according to the program need. consider the following examples:

Java thread

In the above programming example

t= new thread (this, threadname)

this is another version of overloaded constructor of java thread here 2nd parameter “threadName” specifies the name of the thread.


IsAlive() and join() method in Java:

as i hav’t discussed about a point that main thread should be end at the last, this means all child threads terminate 1st then at last main java thread should terminate to accomplish that main thread should terminate at last for that we give prior delay than child thread so that main thread end at last. In previous examples main thread given the delay more than child thread ,

thread. sleep (1000);

In short this is a good programming practice that main thread should terminate at 1st. giving delay more in main () is not a satisfactory solution. How a thread knows about another thread has ended.

There are two ways exist to determine whether a java thread has finished.

(1) isAlive

(2) join ()

isAlive():

we call isAlive () on the java thread the isAlive () method returns true if the thread upon which it is caled is still running, otherwise it returns false. In short this method gust ensures that a thread is running or finished.

join ():

isAlive() method is occasionally useful, the most common method we use is join(). this method is used to wait for a thread to finish is called join(), this method waits until the thread on which it is called terminates. this means that this method provides a mechanism for main thread to terminate at the end. this method is called with threads to wait for that thread to terminate the following example will clean the concept of isAlive and join() method.

Java thread

Java thread priorities:

all threads have a priority which determines which java thread is executed when several java threads are writing for their turn, this makes it possible to give one thread more access to processor resources than another. In theory higher priority java threads get more  CPU time than lower priority threads. the amount of CPU time that a thread gets often depends on several factors besides priority. For instance, when a lower-priority thread is running and a higher priority thread. resumes (for sleeping) or waiting (i/o) then it prompts the lower-priority thread. In case of equal priority, the thread gets equal access to the CPU.

In java, there are possible values for java thread priority that are defined in static date members of the class thread. these members are off type int 2nd declared as final. the maximum priority is defined by the member max priority which has the value IO. the minimum priority is MIN PRIORITY defined as 1, the value of default priority that is assigned to the main thread in a program is NORM PRIORITY is set to 5, when you create a, to priority will be the same as that of the thread that created it. we can modify the priority by calling the setpriority() method for the thread object. final void setpriority(int level). this level provides specifies the new priority. we can give any number in the range 1 < level If you give less than 1 or more than 10 then  IllegalArgumentExcception will be thrown.


How to use thread priority in Java programming:

Java thread

Now exiting the main thread As in the constructor argument, 1st argument represents the java thread name  2nd argument represents priority 3rd the argument represents delay As I have no such a good program in my mind at that time to demonstrate the setpriority method. you can run the above program and make some experiment by changing delay and priority parameter than you will see how its works. Above thread 3 has a higher priority that’s why it got CPU 1st.

Synchronization in Java:

when two or more java threads need access to shared resources. they need some way to ensure that the resources should be used only by one java thread at a time. suppose we have multiple java threads in a program, suppose take a resource CPU i.e In synchronization only one  thread can access the CPU at a time until to completion, no other threads can get the CPU until a thread does not complete. synchronization is based on the concept of ‘monitor’. A ‘monitor’ is an object that is used a mutually exclusive lock Only one thread can own a monitor at a given time. once a java thread gets or own a monitor then thin thread acquires a lock. All other threads attempting to enter the locked monitor will be suspended until the first thread exits the monitor. there are two ways to synchronize our code. both involve the use of the Synchronized keyword.

Using Synchronized method:

All objects have their own implicit monitor associated with them. to enter a objects monitor just call a method that has been modified with the ‘synchronized’ keyword. while the code for a method is in a synchronized method, all other threads that try to call it, they must wait. consider the following examples. let we see  without synchronization:

Java thread



Explanation:

the above example is without synchronization. the above program has three classes. the first one, Callme, has a single method call(), the call() method takes a string parameter i.e msg

void call (string msg);

this method tries to prints the message in b/w brackets the 2nd class has a constructor, which receives a reference to an instance of class callme and a string and then creates a new java thread. In 3rd class sync we define method main(). In main (), an object target of class is instantiated i.e reference of class callme is assigned to target. Then ob1 is instantiated of class callme we pass a reference target and a string message ‘hello’ to the constructor. here constructor invoked. of class caller. call() method prints ‘[hello’ and when control comes in try block it becomes sleep for 1 second. the constructor of the next class,caller takes a reference to an instance of the callme class and a string. the constructor als create a new java thread which call thin object run() method. the thread is started immediately. the run () method of caller calls the call() method on the target instance of calme, passing in the msg string. here again call() method prints synchronized and then again thin thread passes for one second the process will be the same for obj3 and finally closing brackets will print. As we saw , by calling sleep(), the call() method allows execution to switch to another thread. this results in the mixed up result of the three messages strings.

In above program every thread tries to complete itself to fix the proceeding , you must serialize access to call(). that is, you must restrict its access to only one java thread at a time, to the this , we simply need to precede call’s definition with the keyword synchronized class callme {

i.e synchronized void callme (string msg)

{

}

thin prevents other threads from entering call() while another java thread using it, the new output will be

[hello]

[synchronized]

[word]

The Synchronized Statement:

this is the 2nd approach to synchronize the threads. here we use synchronized block

Synchronized (object)

{

statements to be synchronized

}

here , object is a reference to the object being synchronized. if you want to synchronize only a single statement, then early braces are optional. here is an alternative version of the preceding examples, using synchronized block within run() method.


Related Article:

Exception Handling in Java and Types of Exceptions in Java

Recommended For You

About the Author: Fawad

My name is Shahzada Fawad and I am a Programmer. Currently, I am running my own YouTube channel "Expertstech", and managing this Website. My Hobbies are * Watching Movies * Music * Photography * Travelling * gaming and so on...

Leave a Reply

%d bloggers like this: