In this concept called Java Thread, we are going to refer about two basic units of execution Process and Thread. Java threads also has concurrency programming concerned with it.
seen from Poland
seen from China
seen from China
seen from China
seen from China
seen from China

seen from United States

seen from United States
seen from Malaysia
seen from Germany
seen from Ecuador

seen from Netherlands

seen from Poland

seen from Malaysia
seen from Netherlands
seen from China

seen from Malaysia

seen from Philippines

seen from United States
seen from China
In this concept called Java Thread, we are going to refer about two basic units of execution Process and Thread. Java threads also has concurrency programming concerned with it.
New Post has been published on heapload
New Post has been published on http://heapload.com/computer-science/introduction-to-java-programming
Introduction to Java Programming
Introduction to Java Programming
Introduction to Java Programming
Java is one of the most popular programming languages professionals use today. Java was introduced with the intention to write code once and execute it on multiple platforms.
Development in Java requires programming understanding, Java environment(JRE & JDK), Java IDE and Java virtual machine(JVM).
Why only Java:
Platform independent:
Java applications are executed on Java virtual machine giving an illusion that the application is actually running on operating system. Operating system treats JVM as a process and assign resources accordingly. Due to this security feature, Java sometimes also known as “managed programming language“.
JVM for each platform has different implementations, but works exactly the same. This makes Java programs highly portable.
Introduction to Java Programming
Garbage Collector:
JVM also manages resource allocation and de-allocation automatically. Java applications are closely monitored and if there is any resource that is not necessary, the garbage collector automatically deletes it.
Object-orientated programming language:
Java takes everything as objects, except the primitive data types. Java supports better software design, different way of thinking about software, allow domain experts to participate in software design phase, easier to extend and much more.
Advance Features:
Java is enriched with many advance features like frameworks, faster development cycle since linking is not required, avoids memory leaks (failing to free memory that will no longer be used), Web-based applications, common interface to applications/data inside and outside company, Distributed Applications, Networking supports TCP and UDP sockets that can access remote data using a variety of protocols, multi-threading etc.
Introduction to Java Programming
Introduction to Java Programming
Introduction to Java Programming Introduction to Java Programming Java is one of the most popular programming languages professionals use today. Java was introduced with the intention to write code once and execute it on multiple platforms. Development in Java requires programming understanding, Java environment(JRE & JDK), Java IDE and Java virtual machine(JVM). Why only Java: Platform…
View On WordPress
Multithreaded Quick Sort
Quick sort is a classic example where we can use multiple threads, since execution proceeds on separate paths on separate segments. You can read about classic Quick Sort here.
Quick Sort Steps
1. Select an element as pivot (preferable the last element).
2. Shift the pivot such that all elements before it are smaller and after it after bigger (Pivot reaches correct position)
3. Sort the two segments (Before Pivot and After Pivot) separately
Now check the last step, The two segments can be sorted and processes by 2 separate Threads easily as they don't depend on each other. In turn they can spawn more segments and more threads. For this we can use ThreadPool.
Multi-threaded Quick Sort Steps
1. Select an element as pivot (preferable the last element).
2. Shift the pivot such that all elements before it are smaller and after it after bigger (Pivot reaches correct position)
3. Sort the two segments (Before Pivot and After Pivot) separately via Two Threads
INPUT
2
6
7
5
3
1
8
4
PROCESSING
2
6
7
5
3
1
8
4
2
8
7
5
3
1
4
6
2
1
7
5
3
4
8
6
2
1
3
5
4
7
8
6
2
1
3
4
5
7
8
6
THREAD 1
2
1
3
THREAD 2
5
7
8
6
1
2
3
5
7
6
8
5
6
7
8
FINAL RESULT
1
2
3
4
5
6
7
8
What is a Thread?
Thread relates to running of a program. A Thread is a single chain of execution within a program.
This above start to end path within a program is called a Thread. These steps can do a number of operations. For example if we are adding two numbers input by the user. This thread execution will comprise of the below steps:
1. Asking user for the input 1
2. Asking user for the input 2
3. Adding the two inputs
4. Printing the final sum.
A single program can have multiple executions in parallel. As in multiple threads. For example finding the sum of 10 input numbers.
Two separate threads can take 5 inputs separately and add them up. At the end, the two results can be added together to get the final sum. It's not that work speed increases magically. It's just a illusion, a trick by a magician.
Salient Features of a Thread
1. Thread is like a sub-process. Multiple thread paths can exist within a single process.
2. All threads share the same resources (memory, variables) within a process. This can result into conflict, hence needs to be handles carefully.
3. Apart from shared resources, each thread has its own stack space where it stores variables local to it.
4. One can argue that we can create multiple processes, then why is the need for multiple threads. You can read about it here. Multiple threads v/s Multiple processes.
Why we need Threads
As the time progress, man is becoming more and more impatient. In today's world of instant food, we want instant results. Gone are the time of batch processing and waiting days for a result. We like the program to finish execution asap.
This is the major reason why we need threads. Threads aid in executing the program faster than before.
In real life also we do multiple things at the same time. A background process of breathing/heartbeat goes on while we perform daily chores. In office we type and talk at the same time. Similarly we like our program to do multi-tasking. This is achieve via Threads.
Before are few scenarios when usefulness of Threads become evident.
Case 1: Website and User Experience (Background Processing)
Consider a website running on a single thread. It takes an input from the user. While it is processing that input, what happens to the website? Use sees a hanged website. So much for user experience.
Solution: When website takes and input, a separate thread can work in background and do the processing, while user experience remains unhindered, enriching the overall quality.
Case 2: Query to a Database (Asynchronous Processing)
Consider a database call from a program. While database is taking its time to respond, the program is sitting is doing no processing. This slows down the overall execution.
Solution: Database query can be done by a separate thread, which waits for the result to be back. Overall it looks asynchronous. Program keeps on doing it's independent processing whilst, a separate thread id waiting for the Database results to be back.
Case 3: Multiple Processors
With the advent of multiple processors, single threaded programs are anyways at a loss. Parallel executions can occur in separate processors. To utilize that, multi-threaded code is a must.
Case 4: Simple Code
Just like recursion, which is difficult to understand but code becomes extremely simple. Same is the case with multiple threads. Code becomes extremely simple to write and modular. If we can divide our execution in separate paths, we should go for threads.
Programming example of multi-threading making things easier is Multithreaded QuickSort.
Multiple threads v/s Multiple processes
A legitimate question occurs that is thread is just like a process, why don't we create multiple processes? Why do we create multiple threads?
There are a few reasons.
Consider it just like an evolutionary process. First there were just processes. It lead to the below shortcomings.
1. If we create multiple processes which should share same resources, coding for it was a cumbersome process.
2. Memory wise too, creating a new processes requires more resources, than creating a separate thread, as essentials (memory, files etc) are shared by all threads.
It lead to the creation of threads. The code remains a single unit. And multiple sub-processes are spawned.
You can consider it like, if 2 small packages can be bundled up and send via courier. Why to send two different couriers.
Two different couriers require:
1. Creating two separate records and tracking numbers.
2. Two separate outer packing material is required.
3. Packing material comes in standard size, hence small package are also packed into big envelopes, which is wastage.
Single courier
1. If delivery address is same, it's better to package them together.
2. Single record and tracking.
3. Single packing material and less wastage.
Three Elephants v/s One Elephant and Two rats
Understand it by another example. When we can do with one elephant and two small rats. It is better than three big elephants.
WAIT() NOTIFY() SHORTCOMING: SINGLE WAIT QUEUE
There is an inherent drawback of wait(), notify() methods in Java.
As we are aware every Object in Java is associated with a Entry Queue and a Wait Queue. When a thread reaches a synchronized block, it will wait on the Entry Queue of the Object if any other Thread already has the lock. Once it acquires the lock, does its processing, calles Object.wait(), it waits on Wait Queue of the Object. When some other Thread calls Object.notify(), one of the threads waiting on the Wait Queue is moved to the Entry queue of the Object, where it fights for the lock on the Object (with all other Threads waiting at the Entry Queue).
The shortcoming is that wait is not a conditional wait. Every object has just one wait queue.
So if a Object.notify() is called, of all threads waiting on wait queue, any one thread at random is moved to the entry queue. There is no direct way to notify a particular Thread. What we do is a workaround. Instead of Object.notify(), we call Object.notifyAll(), so as all threads are moved from Object’s wait queue to entry queue. Object.wait() call is made in a while loop each checking on a particular condition. So we attach each Object.wait() with a particular condition, as below.
1
2
3
4
5
6
7
8
9
10
11
12
13
//Thread1
synchronized(object) {
while(!condition1) {
object.wait();
}
}
//Thread 2
synchronized(object) {
while(!condition2) {
object.wait();
}
}
When some other Thread sets condition2 = true (while condition1 is still false) and calls object.nofityAll(), both the above Threads which are waiting on the wait queue of the object, are moved to entry queue of the object. Since wait() is in spinning while loop, so Thread1 (if it gets the lock) again calls object.wait() while the Thread2 (if it gets the lock) comes out of the loop starts the processing.
The drawback you see, is unnecessary processing (looping once and checking for condition) in Thread1 and also unnecessary moving of Thread1 from wait queue of Object to entry queue to back. Thread1 wanted to awaken only ifcondition1 == true and Object.notify() is called (not just @ Object.notify()). What would have been nice if there was provision for Conditional Monitor Objects with each having its own wait queue. Something like,
1
2
3
4
5
6
7
8
9
//Thread 1
synchronized(object) {
object.wait(condition1);
}
//Thread 2
synchronized(object) {
object.wait(condition2);
}
Here wait is now waiting on a condition. I have seen some good implementations which are provided for above problem. One being here.