JAVA PROGRAMMING
UNIT-IV
GRAPHICS
MULTITHREADING
I/O STREAM
CLASSES
UNIT IV:
Graphics: working with Graphics-Drawing
Line, Rectangles, Ellipses, Polygon.
Multithreading: Lifecycle-creating, Running
threads, thread priority, Methods in thread
class, thread model.
I/O Stream classes, Byte stream, I/O, file I/O
streams. Character stream: Reader, Writer,
FileReader, FileWriter, Random access files.
MULTITHREADING
• Java Provides built-in support for multithreaded
programming ;
• A multithreaded program contains two or more parts that
can be run concurrently;
• Each thread defines a separate path of execution .Thus,
multithreading is a specialized form of multitasking;
• In Multithreading , Two distinct types of multitasking:
• Process – Based : is a multitasking and allows to run
two or more programs concurrently;
For e.g., Java Compiler run the Java Program same
time Text Editor used by user.
• Thread – Based : is a multitasking and the thread is
the smallest unit of dispatchable code. It means that a
single program can perform two or more tasks
simultaneously; For e.g., A Text Editor can format
text at the same time that it is printing and 2 separate
threads are used;
Advantages of Threads:
It increases the speed of the execution;
It allows to run more tasks
simultaneously;
It reduce the complexity of large
programs;
It maximize CPU utilization;
Single Thread :
• A Single Thread is a program that has a single
flow of control executes sequentially;
Multithread :
• It enables to use multiple flows of control in
program;
• A program contains multiple flow of control is
known as Multithreaded program;
• Each flow of control may be a separate tiny
program known as Thread that runs in parallel;
• One or more threads can run concurrently and
share the resources;
• Java threads are subprograms of the main
program and share the same memory;
• Threads are extensively used in Java-Enabled
Browsers such as HotJava.
• These browsers can download a file to the local
computer, display a web page in the window ,
output another webpage to printer;
Thread can be of
Thread class
Thread Methods
Life cycle of a Thread
Thread Priorities
Thread Scheduling
Thread Synchronization
Creating a Thread
Implementing Runnable
Interthread Communication
Thread Class:
• Thread is a class and it contains
constructors and methods needed for
creating threads. Thread class is used
java.lang Package;
• Constructors are as,
i) public Thread(String ThreadName)
ii) public Thread()
Thread Methods :
The Thread Methods are as follows:
* run()*start() *sleep() *isAlive()
*stop() *wait() *yield().
run() : This method should be overridden in
thread extended from the super class Thread.
public void run()
{ Statements related to a particular
thread. }
Start() : This method is used to start the run()
method. If the method is already started it
throws illegalThreadStateException.
void
start() ;
Sleep():
This method is used to suspends a thread for a
specified amount of Time (in milliseconds).
static void sleep(long int a) ;
isAlive() : This method is used to determine the
thread is running or not;
static void sleep(long int a) ;
stop(): This method is used to stop the running
thread;
void
start() ;
Wait(): This method is used to stop the currently
running thread.
void
start() ;
yield(): This method is used to bring the stopped
current thread to run mode.
void
start() ;
Life cycle of a Thread:
• Every thread moves through several states
from its creation to its termination;
• The States of thread are as,
* new
*ready Dead
*running Runnin Waitin
Ne Ready g
g
w
*waiting
*dead
After the creation of a Thread, it will be in the new
state;
After start() method of Thread class is executed , it will
move to the ready state;
When the JVM(Java Virtual Machine) selects it for
execution it will move to the running state;
When the Thread completes its execution , it will move
to the dead state;
A Thread instructed to wait() , it moves to the waiting
state ;
When the waiting is over , the Thread once again moves
to the ready state;
Creating a Thread :
• User can create a thread by instantiating an object
of type Thread.
• Java defines two ways which can be accomplished:
To implement the Runnable Interface.
To extend the Thread class itself.
Implementing Runnable :
• It is easiest way to create a thread that implements
the Runnable interface.
• Runnable abstract a unit of executable code. It
Public void run();
need to call run();
• Inside run(), it constitutes the new
thread .run() call other methods and it is entry
point for another concurrent thread of
execution within user program.
• If run() returns then thread will end;
Syntax :
Thread (Runnable threadobj , String
threadName);
} }
E.g., // Runnable class
class Table implements OUTPUT:
Runnable
{
public void run()
{ for(int i=1;i<=10;i++)
{ System.out.println(i+"*6="+
(i*6));}
}
}
public class FirstThread
{
public static void main(String
args[])
{ Table r=new Table();
Thread t=new Thread(r);
t.start();
Thread Priorities :
• The user can set the priority for threads. This is
called Thread Priority. This is done by using the
method setPriority() which is a member of
Threadvoid setPriority(int level);
class.
• The value of priority level should be between
MIN_PRIORITY(1),MAX_PRIORITY(10)and
NORM_PRIORITY and its default value is 5 .
void getPriority();
public class ThreadPriority extends Thread
{ public void run()
{
System.out.println("run() method"); OUTPUT
String threadName=Thread.currentThread().getName();
Integer threadPrio = Thread.currentThread().getPriority();
System.out.println(threadName + " has priority " +
threadPrio);
}
public static void main(String[] args) throws
InterruptedException
{
ThreadPriority t1 = new ThreadPriority();
ThreadPriority t2 = new ThreadPriority();
ThreadPriority t3 = new ThreadPriority();
t1.setPriority(Thread.MAX_PRIORITY);
t2.setPriority(Thread.MIN_PRIORITY);
t3.setPriority(Thread.NORM_PRIORITY);
t1.start();
t2.start();
t3.start();
}
}
Synchronization:
• Synchronization in java is the capability to control the
access of multiple threads to any shared resource.
• It is to allow only one tread to access the same resource.
• Synchronization is using Java keywords "synchronized"
and "volatile”.
• Synchronization is mainly used to ,
1. To prevent thread interference
2. To prevent consistency problem
• Types of Synchronization :
1. Process Synchronization
2. Thread Synchronization
• When more than one thread tries to access a particular
resource, synchronization is overcome this problem.
• During Synchronization , java creates a monitor for the
thread and it calls the resource first and hands it over to it.
• Using Synchronized method, it does not allow other thread
to access the same resource.
• JVM guarantees that Java synchronized code will only be
executed by one thread at a time.
Example program:
//Example of java synchronized public void run()
method { t.printTable(2); } }
class Table{ class MyThread2 extends Thread
synchronized void printTable(int { Table t;
n) MyThread2(Table t)
{//synchronized method { this.t=t; }
for(int i=1;i<=10;i++) public void run()
{ { t.printTable(20); } }
System.out.println(i+"*"+n+"=" public class TestSynchron{
+n*i); public static void main(String
try{ Thread.sleep(400); args[]){
}catch(Exception e) Table T = new Table();//only one
{System.out.println(e);} object
} System.out.print("~~~~~~~\ MyThread1 t1=new
n"); MyThread1(T);
} } MyThread2 t2=new
class MyThread1 extends Thread MyThread2(T);
{ t1.start();
E:\RAMJAVA>javac TestSynchron.java(using synchronized keyword)
E:\RAMJAVA>java TestSynchron
1*2=2
2*2=4
3*2=6
4*2=8
5*2=10
6*2=12
7*2=14
8*2=16
9*2=18
10*2=20
~~~~~~~
1*20=20
2*20=40
3*20=60
4*20=80
5*20=100
6*20=120
7*20=140
8*20=160
9*20=180
10*20=200
~~~~~~~ Without using synchronized method,
the output like this
Explanation:
• Let us consider only one object access two threads;
• Assume that is accessing the synchronized method
printTable().
• Two separate thread classes named as mythread1 and
mythread2;
• Only one object for super class can access for all; and it has
synchronized method ;
• It is regulate the threads in order wise execute it. First
table 2 is display the output and next is table 20.
• In multithreading concept , both threads are run
concurrently; user can apply synchronized method is to
allow only one thread to access.
Thread Scheduling :
• Scheduling is a process of allocating CPU for the
threads in the order of their priority by the operating
system.
• OS select the higher priority thread and allocate CPU till
it computer.
• If more than one threads are having same priority it
allocates the CPU in round robin method. E.g., Token in
Hospital.
Interthread Communication :
• It depicts inter-process communication .
• Communication between threads is known as
interthreaded communication;
• Java provides well designed inter – process
mechanism using the following methods, wait(),
notify() and notifyAll();
• wait() method tells the calling thread to exit and
enter thevoid
final ‘sleep’ state
wait() till some other thread enters
throws
InterruptedException
and calls notify();
• notify() wakes up thread that called wait() on the
same object;
final void notify();
• notifyAll() wakes up or notifies all the threads that
call wait() on the same object ; one of the threads
will be granted access.
final void notifyAll();
Thank you