JAVA UNIT-4
JAVA UNIT-4
JAVA PROGRAMMING GE
\*
UNIT-4(Chapter-1)
Multithreading
Note:The Boolean, Character, and Number classes--these classes are "wrapper" classes for the
primitive types. You use these classes in applications where the primitive types must be stored as
objects. Note also the Throwable class--this is the root class for all exceptions and errors.
Multithreading:
● Multithreading in java is a process of executing multiple threads simultaneously.
● Thread is basically a lightweight sub-process, a smallest unit of processing.
Multiprocessing and multithreading, both are used to achieve multitasking. But we use
multithreading than multiprocessing because threads share a common memory area. They
don't allocate separate memory area so saves memory, and context-switching between the
threads takes less time than process.
● Java Multithreading is mostly used in games, animation etc.
1) It doesn't block the user because threads are independent and you can perform multiple
operations at same time.
3) Threads are independent so it doesn't affect other threads if exception occur in a single
thread.
Multitasking:
● Switching from one process to another require some time for saving and loading
registers, memory maps, updating lists etc.
● Thread is lightweight.
Uses of Threads:
⮚ Threads are used to design server side programs to handle multiple clients at a time.
⮚ Threads are used in games and animations.
⮚ We can reduce the idle time of processor.
⮚ Performance of processor is improved.
⮚ Reduces interferences between execution and user interface.
The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
1. New State:
The thread is in new state if you create an instance of Thread class but before the
invocation of start() method.
The thread is in runnable state after invocation of start() method, but the thread scheduler
has not selected it to be the running thread.
3. Running State:
The thread is in running state if the thread scheduler has selected it.
This is the state when the thread is still alive, but is currently not eligible to run.
When a Java program starts up, one thread begins running immediately. This is usually called the
main thread of your program, because it is the one that is executed when your program begins.
• Often, it must be the last thread to finish execution because it performs various shutdown
actions.
Although the main thread is created automatically when your program is started, it can be
controlled through a Thread object. To do so, you must obtain a reference to it by calling the
method currentThread( ), which is a public static member of Thread.
This method returns a reference to the thread in which it is called. Once you have a reference to
the main thread, you can control it just like any other thread.
class Current
IV.Creating Threads
We know that in every java program, there is a main thread available already. Apart from this
main thread, we can also create our own threads in a program. The following steps should be
used.
⮚ Write a class that extends “Thread” class or implements “Runnable” interface this is
available in lang package.
Class Myclass extends Thread
(or)
⮚ Write public void run () method in that class. This is the method by default executed by
any thread.
public void run()
Statements;
⮚ Create an object to my class, so that the run() method is available for execution.
Myclassobj=new Myclass();
}
Class Demo
{
public static void main(String args[])throws
InterruptedException
{
Myclassobj=new Myclass();
Thread t=new Thread(obj);
t.start();
}
}
Thread.MIN_PRIORITY value is 1
Thread.NORM_PRIORITY value is 5
If we want to terminate only the thread that is running the code inside run() method, we should
devise our own mechanism. if we press Ctrl+C, we are abnormally terminating the program. This
is dangerous. Abnormal program termination may cause loss of data and lead to unreliable
results. So, we should terminate the thread only, not the program. how can we terminate the
thread smoothly is the question now.
What is the difference between ‘extends thread’ and ‘implements Runnable’ ? which one is
advantageous?
‘extends thread’ and ‘implements Runnable’-both are functionally same. But when we write
extends Thread, there is no scope to extend another class, as multiple inheritance is not supported
in java.
If we write implements Runnable, then still there is scope to extend another class.
This is definitely advantageous when the programmer wants to use threads and also wants to
access the features of another class.
Example:
Let us think that only one berth is available in a train and two passengers (threads) are asking for
that berth in two different counters. The clerks at different counters sent a request to the server to
allot that berth to their passengers. Let us see now to whom that berth is allotted.
Program: Write a program to create multiple threads and make the threads to action single
object.
//Thread unsafe –Two threads acting on same object.
Please observe the output in the preceding program. It is absurd. It has allotted the same berth to
both the passengers. Since both the threads are acting on the same object simultaneously, then
the result is unreliable.
Output:
When a thread is acting on an object preventing other threads from acting on the same
object is called Thread Synchronization or Thread Safe. The object on which the threads are
synchronized is called ‘synchronized object’.
Example:
It is like a room with only one door. A person has entered the room and locked form it from
behind. The second person who wants to enter the room should wait till the first person comes
out.
In this way, a thread also locks the object after entering it. Then the next thread cannot enter it
till the first thread comes out. This means the object is locked mutually on threads. So, this object
is called ‘mutex’.
synchronized (obj_lock)
{
statements;
}
Here, object represents the object to be locked or synchronized. The statements inside the
synchronized block are all available to only one thread at a time. They are not available to
more than one thread simultaneously.
⮚ To synchronize an entire method code we can use synchronized word before method
name
synchronized void method ()
{
Stmts;
}
Now the statements inside the method are not available to more than one thread at a time.
This method code is synchronized.
Output:
Output:
Press Cntrl+C to exit
VI.Thread Priority
Each thread has a priority. Priorities are represented by a number between 1 and 10. In most
cases, thread scheduler schedules the threads according to their priority (known as preemptive
scheduling). But it is not guaranteed because it depends on JVM specification that which
scheduling it chooses.
}
public static void main(String args[])
{
Priority m1=new Priority();
Priority m2=new Priority();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}
}
}
}
class mainforalive
{
public static void main(String ar[])
{
mythread obj=new mythread();
mythread obj1=new mythread();
obj.start();
System.out.println(obj.isAlive());
Output:
try
Thread.sleep(3000);
catch(InterruptedException ie)
class withjoin
obj.setName("Thread1");
obj1.setName("Thread2");
obj.start();
try
obj.join();
catch(InterruptedException ie)
obj1.start();
Output:
}
}
public static void main( String args[ ] )
{
SRDemo obj = new SRDemo();
SRDemo obj1 = new SRDemo();
obj.setName("First Thread");
obj1.setName("Second Thread");
obj.start();
obj1.start();
try
{
Thread.sleep( 1000 );
obj.suspend();
System.out.println(" First thread Suspending 1ms");
Thread.sleep( 1000 );
obj.resume();
System.out.println(" First thread Resuming");
Thread.sleep(2000);
obj1.suspend();
System.out.println("Second thread Suspending 2ms");
Thread.sleep(1000);
obj1.resume();
System.out.println("Second thread Resuming");
}
catch(InterruptedException e)
{
}
}
}
Output:
First thread Suspending 1ms
Second Thread:0
First thread Resuming
First Thread:0
Second Thread:1
First Thread:1
Second thread Suspending 2ms
Second Thread:2
Second thread Resuming
First Thread:2
There are simply three methods and a little trick which makes thread communication possible.
First let's see all the three methods listed below:
These methods have been implemented as final methods in Object, so they are available in all
the classes. All three methods can be called only from within a synchronized context.
Example:
Here we are discussing an example which has two threads. One thread is printing even numbers
from 0 to 20, while the other thread is printing odd numbers from 0 to 20. Our aim is to print
even and odd numbers alternately.
}
}
}
}
}
}
}
}
}
}
class ex
{
Output:
Odd number = 1
Even number = 2
Odd number = 3
Even number = 4
Odd number = 5
Even number = 6
Odd number = 7
Even number = 8
Odd number = 9
Even number = 10
Odd number = 11
Even number = 12
Odd number = 13
Even number = 14
Odd number = 15