Java Thread: multiple threading, implement Runnable and java Synchronization

(Last Updated On: April 2, 2021)

Java thread:

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

Amazon Purchase Links:

Top Gaming Computers

Best Laptops

Best Graphic Cards

Portable Hard Drives

Best Keyboards

Best High Quality PC Mic

Computer Accessories

*Please Note: These are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way!

Parallel programming:

Programming with java threads is called parallel programming it means more than one tasks are running in parallel. As we know CPU processes 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 in parallel.

Where java threading is used:

Mostly in animation graphics and such other cases e.g. taking an example of typing tutor. Multiple java threads are used in typing tutor. We now consider only two java threads. One java thread is used to move the alphabet from top to down in the screen and another java thread is used from typing moving of text while the second process take same time uses giving inputs but one performed parallel. To understand more about java 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 set of instructions but java thread is a single sequence stream within a process.

Sometimes java thread is also called a light weight 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 have its own data memory location but all related java threads can share 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 set of tasks but the problem arises when two or more task are to be performed concurrently as without multiple java threading concept. The process is consist of one thread so in such situation more than one task cannot be performed  without multiple java threading concept. 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 save 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 java thread from which other “child” thread are created.

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

Now we see the main thread i.e. the information about 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 Java 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 abstract method declared in Runnable interface then only those classes can implement runt() 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 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 call run method.

example here:

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, main thread again active and executes and then again sleep for 1 second.

this process goes on as above output.

t= new thread (this);

here this means 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 here

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 create only one thread i.e there are total two java threads one is main thread which is created automatically and 2nd one is 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.


Is Alive () and join () method:

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

In java there are possible values for java thread priority are defined in static date members of the class thread. these members are off type int 2nd declared as final. the maximumpriority 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). these 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.

example program:

Java thread

Now exiting main thread

As in the constructor argument, 1st argument represent java thread name  2nd argument represents priority 3rd argument represent 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. In above thread 3 has higher priority thats why  it got CPU 1st.


Synchronization:

when two or more java threads need access to a 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 java thread can access the cpu at 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 mutually exclusive lock Only one thread can own a monitor at 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 ‘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 create 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 java 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 java thread. this results in the mixed up result of the three messages strings.



In above program every java 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.

Recommended For You

About the Author: Engr Fahad

My name is Shahzada Fahad and I am an Electrical Engineer. I have been doing Job in UAE as a site engineer in an Electrical Construction Company. Currently, I am running my own YouTube channel "Electronic Clinic", and managing this Website. My Hobbies are * Watching Movies * Music * Martial Arts * Photography * Travelling * Make Sketches and so on...

Leave a Reply