SlideShare a Scribd company logo
PROGRAMMING IN JAVA
A. SIVASANKARI
ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER APPLICATION
SHANMUGA INDUSTRIES ARTS AND SCIENCE
COLLEGE,
TIRUVANNAMALAI. 606601.
Email: sivasankaridkm@gmail.com
PROGRAMMING IN JAVA
UNIT – 3
PART II
 METHOD
OVERRIDING
 MULTITHREADING
 SYNCHRONIZATION
 INTER THREAD
COMMUNICATION
 DEADLOCK
A. SIVASANKARI - SIASC-TVM UNIT-3
PROGRAMMING IN JAVA
METHOD OVERRIDING
• If a class inherits a method from its superclass, then there is a chance to override the method
provided that it is not marked final.
• The benefit of overriding is: ability to define a behavior that's specific to the subclass type,
which means a subclass can implement a parent class method based on its requirement.
• In object-oriented terms, overriding means to override the functionality of an existing method.
Rules for Method Overriding
• The argument list should be exactly the same as that of the overridden method.
• The return type should be the same or a subtype of the return type declared in the original
overridden method in the superclass.
• The access level cannot be more restrictive than the overridden method's access level. For
example: If the superclass method is declared public then the overridding method in the sub
class cannot be either private or protected.
• Instance methods can be overridden only if they are inherited by the subclass.
• A method declared final cannot be overridden.
• A method declared static cannot be overridden but can be re-declared.
• If a method cannot be inherited, then it cannot be overridden.
• A subclass within the same package as the instance's superclass can override any superclass
method that is not declared private or final.
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
EXAMPLE
• class Animal {
• public void move() {
• System.out.println("Animals can move"); }}
• class Dog extends Animal {
• public void move() {
• System.out.println("Dogs can walk and run"); }}
• public class TestDog {
• public static void main(String args[]) {
• Animal a = new Animal();
• // Animal reference and object
• Animal b = new Dog();
• // Animal reference but Dog object
• a.move(); // runs the method in Animal class
• b.move(); // runs the method in Dog class }}
This will produce the following result
OUTPUT
• Animals can move
• Dogs can walk and run
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
MULTITHREADING
• Java is a multi-threaded programming language which means we can develop
multi-threaded program using Java. A multi-threaded program contains two or
more parts that can run concurrently and each part can handle a different task at
the same time making optimal use of the available resources specially when
your computer has multiple CPUs.
• By definition, multitasking is when multiple processes share common
processing resources such as a CPU. Multi-threading extends the idea of
multitasking into applications where you can subdivide specific operations
within a single application into individual threads. Each of the threads can run
in parallel. The OS divides processing time not only among different
applications, but also among each thread within an application.
• Multi-threading enables you to write in a way where multiple activities can
proceed concurrently in the same program.
LIFE CYCLE OF A THREAD
• A thread goes through various stages in its life cycle. For example, a thread is
born, started, runs, and then dies. The following diagram shows the complete
life cycle of a thread.
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
LIFE CYCLE OF A THREAD
• New − A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread. It is also referred to as a born thread.
• Runnable − After a newly born thread is started, the thread becomes runnable. A thread in this
state is considered to be executing its task.
• Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for another
thread to perform a task. A thread transitions back to the runnable state only when another thread
signals the waiting thread to continue executing.
• Timed Waiting − A runnable thread can enter the timed waiting state for a specified interval of
time. A thread in this state transitions back to the runnable state when that time interval expires
or when the event it is waiting for occurs.
• Terminated (Dead) − A runnable thread enters the terminated state when it completes its task or
otherwise terminates.
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
THREAD PRIORITIES
• Every Java thread has a priority that helps the operating system determine the order in which
threads are scheduled.
• Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and
MAX_PRIORITY (a constant of 10). By default, every thread is given priority
NORM_PRIORITY (a constant of 5).
• Threads with higher priority are more important to a program and should be allocated
processor time before lower-priority threads. However, thread priorities cannot guarantee the
order in which threads execute and are very much platform dependent.
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
S.No THREAD METHODS & DESCRIPTION
1 public void start()Starts the thread in a separate path of execution, then invokes the run() method
on this Thread object.
2 public void run()If this Thread object was instantiated using a separate Runnable target, the run()
method is invoked on that Runnable object.
3 public final void setName(String name)Changes the name of the Thread object. There is also a
getName() method for retrieving the name.
4 public final void setPriority(int priority)Sets the priority of this Thread object. The possible
values are between 1 and 10.
5 public final void setDaemon(boolean on)A parameter of true denotes this Thread as a daemon
thread.
6 public final void join(long millisec)The current thread invokes this method on a second thread,
causing the current thread to block until the second thread terminates or the specified number of
milliseconds passes.
7 public void interrupt()Interrupts this thread, causing it to continue execution if it was blocked for
any reason.
8 public final boolean isAlive()Returns true if the thread is alive, which is any time after the thread
has been started but before it runs to completion.
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
S.No THREAD METHODS & DESCRIPTION
1 public static void yield()Causes the currently running thread to yield to any other threads of the
same priority that are waiting to be scheduled.
2 public static void sleep(long millisec)Causes the currently running thread to block for at least
the specified number of milliseconds.
3 public static boolean holdsLock(Object x)Returns true if the current thread holds the lock on
the given Object.
4 public static Thread currentThread()Returns a reference to the currently running thread, which
is the thread that invokes this method.
5 public static void dumpStack()Prints the stack trace for the currently running thread, which is
useful when debugging a multithreaded application.
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
CREATE A THREAD BY IMPLEMENTING A RUNNABLE INTERFACE
• If your class is intended to be executed as a thread then you can achieve this by implementing
a Runnable interface. You will need to follow three basic steps −
• As a first step, you need to implement a run() method provided by a Runnable interface. This
method provides an entry point for the thread and you will put your complete business logic
inside this method. Following is a simple syntax of the run() method −
public void run( )
• As a second step, you will instantiate a Thread object using the following constructor −
• Thread(Runnable threadObj, String threadName); Where, threadObj is an instance of a class
that implements the Runnable interface and threadName is the name given to the new
thread.
• Once a Thread object is created, you can start it by calling start() method, which executes a
call to run( ) method. Following is a simple syntax of start() method −
void start();
Example
• class RunnableDemo implements Runnable
• { private Thread t;
• private String threadName;
• RunnableDemo( String name) {
• threadName = name;
• System.out.println("Creating " + threadName );
• }
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
• public void run() {
• System.out.println("Running " + threadName );
• try {
• for(int i = 4; i > 0; i--) {
• System.out.println("Thread: " + threadName + ", " + i);
• // Let the thread sleep for a while.
• Thread.sleep(50); } }
• catch (InterruptedException e) {
• System.out.println("Thread " + threadName + " interrupted."); }
System.out.println("Thread " + threadName + " exiting."); }
• public void start () {
• System.out.println("Starting " + threadName );
• if (t == null) {
• t = new Thread (this, threadName);
• t.start (); } }}
• public class TestThread {
• public static void main(String args[]) {
• RunnableDemo R1 = new RunnableDemo( "Thread-1"); R1.start();
• RunnableDemo R2 = new RunnableDemo( "Thread-2"); R2.start(); } }
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
This will produce the following result
Output
• Creating Thread-1
• Starting Thread-1
• Creating Thread-2
• Starting Thread-2
• Running Thread-1
• Thread: Thread-1, 4
• Running Thread-2
• Thread: Thread-2, 4
• Thread: Thread-1, 3
• Thread: Thread-2, 3
• Thread: Thread-1, 2
• Thread: Thread-2, 2
• Thread: Thread-1, 1
• Thread: Thread-2, 1
• Thread Thread-1 exiting.
• Thread Thread-2 exiting
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
SYNCHRONIZATION
• When we start two or more threads within a program, there may be a situation when multiple
threads try to access the same resource and finally they can produce unforeseen result due to
concurrency issues. For example, if multiple threads try to write within a same file then
they may corrupt the data because one of the threads can override data or while one
thread is opening the same file at the same time another thread might be closing the same file.
• So there is a need to synchronize the action of multiple threads and make sure that only
one thread can access the resource at a given point in time. This is implemented using a
concept called monitors. Each object in Java is associated with a monitor, which a thread can
lock or unlock. Only one thread at a time may hold a lock on a monitor.
• Java programming language provides a very handy way of creating threads and synchronizing
their task by using synchronized blocks. You keep shared resources within this block.
Following is the general form of the synchronized statement
SYNTAX
• synchronized(objectidentifier) { // Access shared variables and other shared resources}
• Here, the objectidentifier is a reference to an object whose lock associates with the monitor
that the synchronized statement represents. Now we are going to see two examples, where we
will print a counter using two different threads. When threads are not synchronized, they print
counter value which is not in sequence, but when we print counter by putting inside
synchronized() block, then it prints counter very much in sequence for both the threads.
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
MULTITHREADING EXAMPLE WITHOUT SYNCHRONIZATION
• Here is a simple example which may or may not print counter value in sequence and every
time we run it, it produces a different result based on CPU availability to a thread.
EXAMPLE
• class PrintDemo
• { public void printCount()
• { try { for(int i = 5; i > 0; i--)
• { System.out.println("Counter --- " + i ); }}
• catch (Exception e) {
• System.out.println("Thread interrupted."); }}}
• class ThreadDemo extends Thread
• { private Thread t; private String threadName;
• PrintDemo PD;
• ThreadDemo( String name, PrintDemo pd) {
• threadName = name;
• PD = pd; }
• public void run() { PD.printCount();
• System.out.println("Thread " + threadName + " exiting.");}
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
• public void start () {
• System.out.println("Starting " + threadName );
• if (t == null) {
• t = new Thread (this, threadName);
• t.start (); } }}
• public class TestThread {
• public static void main(String args[]) {
• PrintDemo PD = new PrintDemo();
• ThreadDemo T1 = new ThreadDemo( "Thread - 1 ", PD );
• ThreadDemo T2 = new ThreadDemo( "Thread - 2 ", PD );
• T1.start(); T2.start(); // wait for threads to end
• try { T1.join(); T2.join(); }
• catch ( Exception e) {
• System.out.println("Interrupted"); } }}
This produces a different result every time you run this program
OUTPUT
• Starting Thread – 1
• Starting Thread – 2
• Counter --- 5Counter --- 4
• Counter --- 3Counter --- 5
• Counter --- 2Counter --- 1 Counter --- 4 Thread Thread - 1 exiting.
• Counter --- 3Counter --- 2 Counter --- 1Thread Thread - 2 exiting.
A. SIVASANKARI - SIASC-TVM
MULTITHREADING EXAMPLE WITH SYNCHRONIZATION
• Here is the same example which prints counter value in sequence and every time we run it, it
produces the same result.
EXAMPLE
• class PrintDemo {
• public void printCount() {
• try { for(int i = 5; i > 0; i--) {
• System.out.println("Counter --- " + i ); } }
• catch (Exception e) {
• System.out.println("Thread interrupted."); } }}
• class ThreadDemo extends Thread {
• private Thread t;
• private String threadName;
• PrintDemo PD;
• ThreadDemo( String name, PrintDemo pd) {
• threadName = name;
• PD = pd; }
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
• public void run() {
• synchronized(PD) {
• PD.printCount(); }
• System.out.println("Thread " + threadName + " exiting."); }
• public void start () {
• System.out.println("Starting " + threadName );
• if (t == null) {
• t = new Thread (this, threadName);
• t.start (); } }}
• public class TestThread {
• public static void main(String args[]) {
• PrintDemo PD = new PrintDemo();
• ThreadDemo T1 = new ThreadDemo( "Thread - 1 ", PD );
• ThreadDemo T2 = new ThreadDemo( "Thread - 2 ", PD );
• T1.start(); T2.start(); // wait for threads to end
• try { T1.join(); T2.join(); }
• catch ( Exception e) {
• System.out.println("Interrupted"); } }}
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
This produces the same result every time you run this program
OUTPUT
• Starting Thread – 1
• Starting Thread – 2
• Counter --- 5
• Counter --- 4
• Counter --- 3
• Counter --- 2
• Counter --- 1
• Thread Thread - 1 exiting.
• Counter --- 5
• Counter --- 4
• Counter --- 3
• Counter --- 2
• Counter --- 1
• Thread Thread - 2 exiting.
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
INTER-THREAD COMMUNICATION
• Inter-thread communication or Co-operation is all about allowing synchronized threads to
communicate with each other. Communication between threads is known is Inter-thread
communication .If we are aware of interprocess communication then it will be easy for you to
understand interthread communication. Interthread communication is important when you
develop an application where two or more threads exchange some information.
• Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running
in its critical section and another thread is allowed to enter (or lock) in the same critical section
to be executed. There are three simple methods and a little trick which makes thread
communication possible. All the three methods are listed below
S.N Method & Description
1 public void wait()Causes the current thread to wait until another thread invokes the
notify().
2 public void notify()Wakes up a single thread that is waiting on this object's monitor.
3 public void notifyAll()Wakes up all the threads that called wait( ) on the same object.
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
EXAMPLE
• class Chat {
• boolean flag = false;
• public synchronized void Question(String msg)
• { if (flag) {
• try {
• wait(); }
• catch (InterruptedException e) {
• e.printStackTrace(); } }
• System.out.println(msg);
• flag = true;
• notify(); }
• public synchronized void Answer(String msg)
• { if (!flag) {
• try {
• wait(); }
• catch (InterruptedException e) {
• e.printStackTrace(); } }
• System.out.println(msg);
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
• flag = false; notify(); }}
• class T1 implements Runnable {
• Chat m; String[] s1 = { "Hi", "How are you ?", "I am also doing fine!" };
• public T1(Chat m1) {
• this.m = m1;
• new Thread(this, "Question").start(); }
• public void run() {
• for (int i = 0; i < s1.length; i++) { m.Question(s1[i]); } }}
• class T2 implements Runnable {
• Chat m;
• String[] s2 = { "Hi", "I am good, what about you?", "Great!" };
• public T2(Chat m2) {
• this.m = m2;
• new Thread(this, "Answer").start(); }
• public void run() {
• for (int i = 0; i < s2.length; i++) {
• m.Answer(s2[i]); } }}
• public class TestThread {
• public static void main(String[] args) {
• Chat m = new Chat();
• new T1(m);
• new T2(m); }}A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
• When the above program is complied
and executed, it produces the following
result
OUTPUT
• Hi
• Hi
• How are you ?
• I am good,
• what about you?
• I am also doing fine!
• Great!
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
DEADLOCK
• Deadlock in java is a part of multithreading. Deadlock can occur in a situation when a thread
is waiting for an object lock, that is acquired by another thread and second thread is waiting
for an object lock that is acquired by first thread. Since, both threads are waiting for each
other to release the lock, the condition is called deadlock.
• Deadlock describes a situation where two or more threads are blocked forever, waiting for
each other. Deadlock occurs when multiple threads need the same locks but obtain them in
different order. A Java multithreaded program may suffer from the deadlock condition
because the synchronized keyword causes the executing thread to block while waiting for the
lock, or monitor, associated with the specified object.
A. SIVASANKARI - SIASC-TVM
A. SIVASANKARI - SIASC-TVM
Ad

More Related Content

What's hot (20)

How to start learning java
How to start learning javaHow to start learning java
How to start learning java
billgatewilliam
 
Advance Java
Advance JavaAdvance Java
Advance Java
Vidyacenter
 
New Features Of JDK 7
New Features Of JDK 7New Features Of JDK 7
New Features Of JDK 7
Deniz Oguz
 
CS6270 Virtual Machines - Java Virtual Machine Architecture and APIs
CS6270 Virtual Machines - Java Virtual Machine Architecture and APIsCS6270 Virtual Machines - Java Virtual Machine Architecture and APIs
CS6270 Virtual Machines - Java Virtual Machine Architecture and APIs
Kwangshin Oh
 
Java 101 Intro to Java Programming
Java 101 Intro to Java ProgrammingJava 101 Intro to Java Programming
Java 101 Intro to Java Programming
agorolabs
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
Oleg Tsal-Tsalko
 
55 New Features in Java SE 8
55 New Features in Java SE 855 New Features in Java SE 8
55 New Features in Java SE 8
Simon Ritter
 
Java 8 Features
Java 8 FeaturesJava 8 Features
Java 8 Features
Trung Nguyen
 
Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...
Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...
Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...
Edureka!
 
Refactoring to Scala DSLs and LiftOff 2009 Recap
Refactoring to Scala DSLs and LiftOff 2009 RecapRefactoring to Scala DSLs and LiftOff 2009 Recap
Refactoring to Scala DSLs and LiftOff 2009 Recap
Dave Orme
 
Hibernate example1
Hibernate example1Hibernate example1
Hibernate example1
myrajendra
 
A Brief, but Dense, Intro to Scala
A Brief, but Dense, Intro to ScalaA Brief, but Dense, Intro to Scala
A Brief, but Dense, Intro to Scala
Derek Chen-Becker
 
Java 101 intro to programming with java
Java 101  intro to programming with javaJava 101  intro to programming with java
Java 101 intro to programming with java
Hawkman Academy
 
Java 8 Features
Java 8 FeaturesJava 8 Features
Java 8 Features
Leninkumar Koppoju
 
Java SE 8 - New Features
Java SE 8 - New FeaturesJava SE 8 - New Features
Java SE 8 - New Features
Naveen Hegde
 
Java For beginners and CSIT and IT students
Java  For beginners and CSIT and IT studentsJava  For beginners and CSIT and IT students
Java For beginners and CSIT and IT students
Partnered Health
 
3 jdbc api
3 jdbc api3 jdbc api
3 jdbc api
myrajendra
 
Core Java introduction | Basics | free course
Core Java introduction | Basics | free course Core Java introduction | Basics | free course
Core Java introduction | Basics | free course
Kernel Training
 
What Is Java | Java Tutorial | Java Programming | Learn Java | Edureka
What Is Java | Java Tutorial | Java Programming | Learn Java | EdurekaWhat Is Java | Java Tutorial | Java Programming | Learn Java | Edureka
What Is Java | Java Tutorial | Java Programming | Learn Java | Edureka
Edureka!
 
System Integration with Akka and Apache Camel
System Integration with Akka and Apache CamelSystem Integration with Akka and Apache Camel
System Integration with Akka and Apache Camel
krasserm
 
How to start learning java
How to start learning javaHow to start learning java
How to start learning java
billgatewilliam
 
New Features Of JDK 7
New Features Of JDK 7New Features Of JDK 7
New Features Of JDK 7
Deniz Oguz
 
CS6270 Virtual Machines - Java Virtual Machine Architecture and APIs
CS6270 Virtual Machines - Java Virtual Machine Architecture and APIsCS6270 Virtual Machines - Java Virtual Machine Architecture and APIs
CS6270 Virtual Machines - Java Virtual Machine Architecture and APIs
Kwangshin Oh
 
Java 101 Intro to Java Programming
Java 101 Intro to Java ProgrammingJava 101 Intro to Java Programming
Java 101 Intro to Java Programming
agorolabs
 
55 New Features in Java SE 8
55 New Features in Java SE 855 New Features in Java SE 8
55 New Features in Java SE 8
Simon Ritter
 
Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...
Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...
Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...
Edureka!
 
Refactoring to Scala DSLs and LiftOff 2009 Recap
Refactoring to Scala DSLs and LiftOff 2009 RecapRefactoring to Scala DSLs and LiftOff 2009 Recap
Refactoring to Scala DSLs and LiftOff 2009 Recap
Dave Orme
 
Hibernate example1
Hibernate example1Hibernate example1
Hibernate example1
myrajendra
 
A Brief, but Dense, Intro to Scala
A Brief, but Dense, Intro to ScalaA Brief, but Dense, Intro to Scala
A Brief, but Dense, Intro to Scala
Derek Chen-Becker
 
Java 101 intro to programming with java
Java 101  intro to programming with javaJava 101  intro to programming with java
Java 101 intro to programming with java
Hawkman Academy
 
Java SE 8 - New Features
Java SE 8 - New FeaturesJava SE 8 - New Features
Java SE 8 - New Features
Naveen Hegde
 
Java For beginners and CSIT and IT students
Java  For beginners and CSIT and IT studentsJava  For beginners and CSIT and IT students
Java For beginners and CSIT and IT students
Partnered Health
 
Core Java introduction | Basics | free course
Core Java introduction | Basics | free course Core Java introduction | Basics | free course
Core Java introduction | Basics | free course
Kernel Training
 
What Is Java | Java Tutorial | Java Programming | Learn Java | Edureka
What Is Java | Java Tutorial | Java Programming | Learn Java | EdurekaWhat Is Java | Java Tutorial | Java Programming | Learn Java | Edureka
What Is Java | Java Tutorial | Java Programming | Learn Java | Edureka
Edureka!
 
System Integration with Akka and Apache Camel
System Integration with Akka and Apache CamelSystem Integration with Akka and Apache Camel
System Integration with Akka and Apache Camel
krasserm
 

Similar to PROGRAMMING IN JAVA-unit 3-part II (20)

unit3multithreadingppt-copy-180122162204.pptx
unit3multithreadingppt-copy-180122162204.pptxunit3multithreadingppt-copy-180122162204.pptx
unit3multithreadingppt-copy-180122162204.pptx
ArunPatrick2
 
unit3 Exception Handling multithreadingppt.pptx
unit3 Exception Handling multithreadingppt.pptxunit3 Exception Handling multithreadingppt.pptx
unit3 Exception Handling multithreadingppt.pptx
ArunPatrick2
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
 
econtent thread in java.pptx
econtent thread in java.pptxecontent thread in java.pptx
econtent thread in java.pptx
ramyan49
 
web programming-Multithreading concept in Java.ppt
web programming-Multithreading concept in Java.pptweb programming-Multithreading concept in Java.ppt
web programming-Multithreading concept in Java.ppt
mcjaya2024
 
7. Multithreading
7. Multithreading7. Multithreading
7. Multithreading
Nilesh Dalvi
 
java.pptxytbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
java.pptxytbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbjava.pptxytbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
java.pptxytbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
jakjak36
 
Threads in java, Multitasking and Multithreading
Threads in java, Multitasking and MultithreadingThreads in java, Multitasking and Multithreading
Threads in java, Multitasking and Multithreading
ssusere538f7
 
CSE 3146 M1- MULTI THREADING USING JAVA .pdf
CSE 3146 M1- MULTI THREADING USING JAVA  .pdfCSE 3146 M1- MULTI THREADING USING JAVA  .pdf
CSE 3146 M1- MULTI THREADING USING JAVA .pdf
universitypresidency
 
OOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxOOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptx
Arulmozhivarman8
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Monika Mishra
 
Multi threading
Multi threadingMulti threading
Multi threading
Ravi Kant Sahu
 
1.17 Thread in java.pptx
1.17 Thread in java.pptx1.17 Thread in java.pptx
1.17 Thread in java.pptx
TREXSHyNE
 
Chap2 2 1
Chap2 2 1Chap2 2 1
Chap2 2 1
Hemo Chella
 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
Rakesh Madugula
 
advanced java ppt
advanced java pptadvanced java ppt
advanced java ppt
PreetiDixit22
 
Unit 5 - Java Multihhhhhhhhhhhhhhhhhhhhaaaaaaaaaaaaaaaaathreading.pdf
Unit 5 - Java Multihhhhhhhhhhhhhhhhhhhhaaaaaaaaaaaaaaaaathreading.pdfUnit 5 - Java Multihhhhhhhhhhhhhhhhhhhhaaaaaaaaaaaaaaaaathreading.pdf
Unit 5 - Java Multihhhhhhhhhhhhhhhhhhhhaaaaaaaaaaaaaaaaathreading.pdf
kassyemariyam21
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Kavitha713564
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Kavitha713564
 
Multithreadingppt.pptx
Multithreadingppt.pptxMultithreadingppt.pptx
Multithreadingppt.pptx
HKShab
 
unit3multithreadingppt-copy-180122162204.pptx
unit3multithreadingppt-copy-180122162204.pptxunit3multithreadingppt-copy-180122162204.pptx
unit3multithreadingppt-copy-180122162204.pptx
ArunPatrick2
 
unit3 Exception Handling multithreadingppt.pptx
unit3 Exception Handling multithreadingppt.pptxunit3 Exception Handling multithreadingppt.pptx
unit3 Exception Handling multithreadingppt.pptx
ArunPatrick2
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
 
econtent thread in java.pptx
econtent thread in java.pptxecontent thread in java.pptx
econtent thread in java.pptx
ramyan49
 
web programming-Multithreading concept in Java.ppt
web programming-Multithreading concept in Java.pptweb programming-Multithreading concept in Java.ppt
web programming-Multithreading concept in Java.ppt
mcjaya2024
 
java.pptxytbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
java.pptxytbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbjava.pptxytbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
java.pptxytbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
jakjak36
 
Threads in java, Multitasking and Multithreading
Threads in java, Multitasking and MultithreadingThreads in java, Multitasking and Multithreading
Threads in java, Multitasking and Multithreading
ssusere538f7
 
CSE 3146 M1- MULTI THREADING USING JAVA .pdf
CSE 3146 M1- MULTI THREADING USING JAVA  .pdfCSE 3146 M1- MULTI THREADING USING JAVA  .pdf
CSE 3146 M1- MULTI THREADING USING JAVA .pdf
universitypresidency
 
OOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxOOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptx
Arulmozhivarman8
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Monika Mishra
 
1.17 Thread in java.pptx
1.17 Thread in java.pptx1.17 Thread in java.pptx
1.17 Thread in java.pptx
TREXSHyNE
 
Unit 5 - Java Multihhhhhhhhhhhhhhhhhhhhaaaaaaaaaaaaaaaaathreading.pdf
Unit 5 - Java Multihhhhhhhhhhhhhhhhhhhhaaaaaaaaaaaaaaaaathreading.pdfUnit 5 - Java Multihhhhhhhhhhhhhhhhhhhhaaaaaaaaaaaaaaaaathreading.pdf
Unit 5 - Java Multihhhhhhhhhhhhhhhhhhhhaaaaaaaaaaaaaaaaathreading.pdf
kassyemariyam21
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Kavitha713564
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Kavitha713564
 
Multithreadingppt.pptx
Multithreadingppt.pptxMultithreadingppt.pptx
Multithreadingppt.pptx
HKShab
 
Ad

More from SivaSankari36 (7)

DATA STRUCTURE BY SIVASANKARI
DATA STRUCTURE BY SIVASANKARIDATA STRUCTURE BY SIVASANKARI
DATA STRUCTURE BY SIVASANKARI
SivaSankari36
 
CLOUD COMPUTING BY SIVASANKARI
CLOUD COMPUTING BY SIVASANKARICLOUD COMPUTING BY SIVASANKARI
CLOUD COMPUTING BY SIVASANKARI
SivaSankari36
 
MOBILE APPLICATIONS DEVELOPMENT -ANDROID BY SIVASANKARI
MOBILE APPLICATIONS DEVELOPMENT -ANDROID BY SIVASANKARIMOBILE APPLICATIONS DEVELOPMENT -ANDROID BY SIVASANKARI
MOBILE APPLICATIONS DEVELOPMENT -ANDROID BY SIVASANKARI
SivaSankari36
 
JAVA BOOK BY SIVASANKARI
JAVA BOOK BY SIVASANKARIJAVA BOOK BY SIVASANKARI
JAVA BOOK BY SIVASANKARI
SivaSankari36
 
MOBILE COMPUTING BY SIVASANKARI
MOBILE COMPUTING BY SIVASANKARIMOBILE COMPUTING BY SIVASANKARI
MOBILE COMPUTING BY SIVASANKARI
SivaSankari36
 
Functional MRI using Apache Spark in Big Data Application
Functional MRI using Apache Spark in Big Data ApplicationFunctional MRI using Apache Spark in Big Data Application
Functional MRI using Apache Spark in Big Data Application
SivaSankari36
 
Java unit1 b- Java Operators to Methods
Java  unit1 b- Java Operators to MethodsJava  unit1 b- Java Operators to Methods
Java unit1 b- Java Operators to Methods
SivaSankari36
 
DATA STRUCTURE BY SIVASANKARI
DATA STRUCTURE BY SIVASANKARIDATA STRUCTURE BY SIVASANKARI
DATA STRUCTURE BY SIVASANKARI
SivaSankari36
 
CLOUD COMPUTING BY SIVASANKARI
CLOUD COMPUTING BY SIVASANKARICLOUD COMPUTING BY SIVASANKARI
CLOUD COMPUTING BY SIVASANKARI
SivaSankari36
 
MOBILE APPLICATIONS DEVELOPMENT -ANDROID BY SIVASANKARI
MOBILE APPLICATIONS DEVELOPMENT -ANDROID BY SIVASANKARIMOBILE APPLICATIONS DEVELOPMENT -ANDROID BY SIVASANKARI
MOBILE APPLICATIONS DEVELOPMENT -ANDROID BY SIVASANKARI
SivaSankari36
 
JAVA BOOK BY SIVASANKARI
JAVA BOOK BY SIVASANKARIJAVA BOOK BY SIVASANKARI
JAVA BOOK BY SIVASANKARI
SivaSankari36
 
MOBILE COMPUTING BY SIVASANKARI
MOBILE COMPUTING BY SIVASANKARIMOBILE COMPUTING BY SIVASANKARI
MOBILE COMPUTING BY SIVASANKARI
SivaSankari36
 
Functional MRI using Apache Spark in Big Data Application
Functional MRI using Apache Spark in Big Data ApplicationFunctional MRI using Apache Spark in Big Data Application
Functional MRI using Apache Spark in Big Data Application
SivaSankari36
 
Java unit1 b- Java Operators to Methods
Java  unit1 b- Java Operators to MethodsJava  unit1 b- Java Operators to Methods
Java unit1 b- Java Operators to Methods
SivaSankari36
 
Ad

Recently uploaded (20)

UPMVLE migration to ARAL. A step- by- step guide
UPMVLE migration to ARAL. A step- by- step guideUPMVLE migration to ARAL. A step- by- step guide
UPMVLE migration to ARAL. A step- by- step guide
abmerca
 
*"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"**"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"*
Arshad Shaikh
 
How to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo SlidesHow to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo Slides
Celine George
 
CNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscessCNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscess
Mohamed Rizk Khodair
 
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptxTERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
PoojaSen20
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
Nguyen Thanh Tu Collection
 
The History of Kashmir Karkota Dynasty NEP.pptx
The History of Kashmir Karkota Dynasty NEP.pptxThe History of Kashmir Karkota Dynasty NEP.pptx
The History of Kashmir Karkota Dynasty NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptxU3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
Mayuri Chavan
 
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living WorkshopLDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDM Mia eStudios
 
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptxANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
Mayuri Chavan
 
All About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdfAll About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdf
TechSoup
 
E-Filing_of_Income_Tax.pptx and concept of form 26AS
E-Filing_of_Income_Tax.pptx and concept of form 26ASE-Filing_of_Income_Tax.pptx and concept of form 26AS
E-Filing_of_Income_Tax.pptx and concept of form 26AS
Abinash Palangdar
 
Botany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic ExcellenceBotany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic Excellence
online college homework help
 
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
Dr. Nasir Mustafa
 
Search Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo SlidesSearch Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo Slides
Celine George
 
2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx
mansk2
 
Myopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduateMyopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduate
Mohamed Rizk Khodair
 
antiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidenceantiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidence
PrachiSontakke5
 
Drugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdfDrugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdf
crewot855
 
UPMVLE migration to ARAL. A step- by- step guide
UPMVLE migration to ARAL. A step- by- step guideUPMVLE migration to ARAL. A step- by- step guide
UPMVLE migration to ARAL. A step- by- step guide
abmerca
 
*"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"**"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"*
Arshad Shaikh
 
How to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo SlidesHow to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo Slides
Celine George
 
CNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscessCNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscess
Mohamed Rizk Khodair
 
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptxTERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
PoojaSen20
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
Nguyen Thanh Tu Collection
 
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptxU3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
Mayuri Chavan
 
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living WorkshopLDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDM Mia eStudios
 
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptxANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
Mayuri Chavan
 
All About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdfAll About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdf
TechSoup
 
E-Filing_of_Income_Tax.pptx and concept of form 26AS
E-Filing_of_Income_Tax.pptx and concept of form 26ASE-Filing_of_Income_Tax.pptx and concept of form 26AS
E-Filing_of_Income_Tax.pptx and concept of form 26AS
Abinash Palangdar
 
Botany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic ExcellenceBotany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic Excellence
online college homework help
 
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
Dr. Nasir Mustafa
 
Search Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo SlidesSearch Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo Slides
Celine George
 
2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx
mansk2
 
Myopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduateMyopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduate
Mohamed Rizk Khodair
 
antiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidenceantiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidence
PrachiSontakke5
 
Drugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdfDrugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdf
crewot855
 

PROGRAMMING IN JAVA-unit 3-part II

  • 1. PROGRAMMING IN JAVA A. SIVASANKARI ASSISTANT PROFESSOR DEPARTMENT OF COMPUTER APPLICATION SHANMUGA INDUSTRIES ARTS AND SCIENCE COLLEGE, TIRUVANNAMALAI. 606601. Email: sivasankaridkm@gmail.com
  • 2. PROGRAMMING IN JAVA UNIT – 3 PART II  METHOD OVERRIDING  MULTITHREADING  SYNCHRONIZATION  INTER THREAD COMMUNICATION  DEADLOCK A. SIVASANKARI - SIASC-TVM UNIT-3
  • 3. PROGRAMMING IN JAVA METHOD OVERRIDING • If a class inherits a method from its superclass, then there is a chance to override the method provided that it is not marked final. • The benefit of overriding is: ability to define a behavior that's specific to the subclass type, which means a subclass can implement a parent class method based on its requirement. • In object-oriented terms, overriding means to override the functionality of an existing method. Rules for Method Overriding • The argument list should be exactly the same as that of the overridden method. • The return type should be the same or a subtype of the return type declared in the original overridden method in the superclass. • The access level cannot be more restrictive than the overridden method's access level. For example: If the superclass method is declared public then the overridding method in the sub class cannot be either private or protected. • Instance methods can be overridden only if they are inherited by the subclass. • A method declared final cannot be overridden. • A method declared static cannot be overridden but can be re-declared. • If a method cannot be inherited, then it cannot be overridden. • A subclass within the same package as the instance's superclass can override any superclass method that is not declared private or final. A. SIVASANKARI - SIASC-TVM
  • 4. PROGRAMMING IN JAVA EXAMPLE • class Animal { • public void move() { • System.out.println("Animals can move"); }} • class Dog extends Animal { • public void move() { • System.out.println("Dogs can walk and run"); }} • public class TestDog { • public static void main(String args[]) { • Animal a = new Animal(); • // Animal reference and object • Animal b = new Dog(); • // Animal reference but Dog object • a.move(); // runs the method in Animal class • b.move(); // runs the method in Dog class }} This will produce the following result OUTPUT • Animals can move • Dogs can walk and run A. SIVASANKARI - SIASC-TVM
  • 5. PROGRAMMING IN JAVA MULTITHREADING • Java is a multi-threaded programming language which means we can develop multi-threaded program using Java. A multi-threaded program contains two or more parts that can run concurrently and each part can handle a different task at the same time making optimal use of the available resources specially when your computer has multiple CPUs. • By definition, multitasking is when multiple processes share common processing resources such as a CPU. Multi-threading extends the idea of multitasking into applications where you can subdivide specific operations within a single application into individual threads. Each of the threads can run in parallel. The OS divides processing time not only among different applications, but also among each thread within an application. • Multi-threading enables you to write in a way where multiple activities can proceed concurrently in the same program. LIFE CYCLE OF A THREAD • A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. The following diagram shows the complete life cycle of a thread. A. SIVASANKARI - SIASC-TVM
  • 6. PROGRAMMING IN JAVA LIFE CYCLE OF A THREAD • New − A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread. • Runnable − After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task. • Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform a task. A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing. • Timed Waiting − A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs. • Terminated (Dead) − A runnable thread enters the terminated state when it completes its task or otherwise terminates. A. SIVASANKARI - SIASC-TVM
  • 7. PROGRAMMING IN JAVA THREAD PRIORITIES • Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled. • Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5). • Threads with higher priority are more important to a program and should be allocated processor time before lower-priority threads. However, thread priorities cannot guarantee the order in which threads execute and are very much platform dependent. A. SIVASANKARI - SIASC-TVM
  • 8. PROGRAMMING IN JAVA S.No THREAD METHODS & DESCRIPTION 1 public void start()Starts the thread in a separate path of execution, then invokes the run() method on this Thread object. 2 public void run()If this Thread object was instantiated using a separate Runnable target, the run() method is invoked on that Runnable object. 3 public final void setName(String name)Changes the name of the Thread object. There is also a getName() method for retrieving the name. 4 public final void setPriority(int priority)Sets the priority of this Thread object. The possible values are between 1 and 10. 5 public final void setDaemon(boolean on)A parameter of true denotes this Thread as a daemon thread. 6 public final void join(long millisec)The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates or the specified number of milliseconds passes. 7 public void interrupt()Interrupts this thread, causing it to continue execution if it was blocked for any reason. 8 public final boolean isAlive()Returns true if the thread is alive, which is any time after the thread has been started but before it runs to completion. A. SIVASANKARI - SIASC-TVM
  • 9. PROGRAMMING IN JAVA S.No THREAD METHODS & DESCRIPTION 1 public static void yield()Causes the currently running thread to yield to any other threads of the same priority that are waiting to be scheduled. 2 public static void sleep(long millisec)Causes the currently running thread to block for at least the specified number of milliseconds. 3 public static boolean holdsLock(Object x)Returns true if the current thread holds the lock on the given Object. 4 public static Thread currentThread()Returns a reference to the currently running thread, which is the thread that invokes this method. 5 public static void dumpStack()Prints the stack trace for the currently running thread, which is useful when debugging a multithreaded application. A. SIVASANKARI - SIASC-TVM
  • 10. PROGRAMMING IN JAVA CREATE A THREAD BY IMPLEMENTING A RUNNABLE INTERFACE • If your class is intended to be executed as a thread then you can achieve this by implementing a Runnable interface. You will need to follow three basic steps − • As a first step, you need to implement a run() method provided by a Runnable interface. This method provides an entry point for the thread and you will put your complete business logic inside this method. Following is a simple syntax of the run() method − public void run( ) • As a second step, you will instantiate a Thread object using the following constructor − • Thread(Runnable threadObj, String threadName); Where, threadObj is an instance of a class that implements the Runnable interface and threadName is the name given to the new thread. • Once a Thread object is created, you can start it by calling start() method, which executes a call to run( ) method. Following is a simple syntax of start() method − void start(); Example • class RunnableDemo implements Runnable • { private Thread t; • private String threadName; • RunnableDemo( String name) { • threadName = name; • System.out.println("Creating " + threadName ); • } A. SIVASANKARI - SIASC-TVM
  • 11. PROGRAMMING IN JAVA • public void run() { • System.out.println("Running " + threadName ); • try { • for(int i = 4; i > 0; i--) { • System.out.println("Thread: " + threadName + ", " + i); • // Let the thread sleep for a while. • Thread.sleep(50); } } • catch (InterruptedException e) { • System.out.println("Thread " + threadName + " interrupted."); } System.out.println("Thread " + threadName + " exiting."); } • public void start () { • System.out.println("Starting " + threadName ); • if (t == null) { • t = new Thread (this, threadName); • t.start (); } }} • public class TestThread { • public static void main(String args[]) { • RunnableDemo R1 = new RunnableDemo( "Thread-1"); R1.start(); • RunnableDemo R2 = new RunnableDemo( "Thread-2"); R2.start(); } } A. SIVASANKARI - SIASC-TVM
  • 12. PROGRAMMING IN JAVA This will produce the following result Output • Creating Thread-1 • Starting Thread-1 • Creating Thread-2 • Starting Thread-2 • Running Thread-1 • Thread: Thread-1, 4 • Running Thread-2 • Thread: Thread-2, 4 • Thread: Thread-1, 3 • Thread: Thread-2, 3 • Thread: Thread-1, 2 • Thread: Thread-2, 2 • Thread: Thread-1, 1 • Thread: Thread-2, 1 • Thread Thread-1 exiting. • Thread Thread-2 exiting A. SIVASANKARI - SIASC-TVM
  • 13. PROGRAMMING IN JAVA SYNCHRONIZATION • When we start two or more threads within a program, there may be a situation when multiple threads try to access the same resource and finally they can produce unforeseen result due to concurrency issues. For example, if multiple threads try to write within a same file then they may corrupt the data because one of the threads can override data or while one thread is opening the same file at the same time another thread might be closing the same file. • So there is a need to synchronize the action of multiple threads and make sure that only one thread can access the resource at a given point in time. This is implemented using a concept called monitors. Each object in Java is associated with a monitor, which a thread can lock or unlock. Only one thread at a time may hold a lock on a monitor. • Java programming language provides a very handy way of creating threads and synchronizing their task by using synchronized blocks. You keep shared resources within this block. Following is the general form of the synchronized statement SYNTAX • synchronized(objectidentifier) { // Access shared variables and other shared resources} • Here, the objectidentifier is a reference to an object whose lock associates with the monitor that the synchronized statement represents. Now we are going to see two examples, where we will print a counter using two different threads. When threads are not synchronized, they print counter value which is not in sequence, but when we print counter by putting inside synchronized() block, then it prints counter very much in sequence for both the threads. A. SIVASANKARI - SIASC-TVM
  • 14. PROGRAMMING IN JAVA MULTITHREADING EXAMPLE WITHOUT SYNCHRONIZATION • Here is a simple example which may or may not print counter value in sequence and every time we run it, it produces a different result based on CPU availability to a thread. EXAMPLE • class PrintDemo • { public void printCount() • { try { for(int i = 5; i > 0; i--) • { System.out.println("Counter --- " + i ); }} • catch (Exception e) { • System.out.println("Thread interrupted."); }}} • class ThreadDemo extends Thread • { private Thread t; private String threadName; • PrintDemo PD; • ThreadDemo( String name, PrintDemo pd) { • threadName = name; • PD = pd; } • public void run() { PD.printCount(); • System.out.println("Thread " + threadName + " exiting.");} A. SIVASANKARI - SIASC-TVM
  • 15. PROGRAMMING IN JAVA • public void start () { • System.out.println("Starting " + threadName ); • if (t == null) { • t = new Thread (this, threadName); • t.start (); } }} • public class TestThread { • public static void main(String args[]) { • PrintDemo PD = new PrintDemo(); • ThreadDemo T1 = new ThreadDemo( "Thread - 1 ", PD ); • ThreadDemo T2 = new ThreadDemo( "Thread - 2 ", PD ); • T1.start(); T2.start(); // wait for threads to end • try { T1.join(); T2.join(); } • catch ( Exception e) { • System.out.println("Interrupted"); } }} This produces a different result every time you run this program OUTPUT • Starting Thread – 1 • Starting Thread – 2 • Counter --- 5Counter --- 4 • Counter --- 3Counter --- 5 • Counter --- 2Counter --- 1 Counter --- 4 Thread Thread - 1 exiting. • Counter --- 3Counter --- 2 Counter --- 1Thread Thread - 2 exiting. A. SIVASANKARI - SIASC-TVM
  • 16. MULTITHREADING EXAMPLE WITH SYNCHRONIZATION • Here is the same example which prints counter value in sequence and every time we run it, it produces the same result. EXAMPLE • class PrintDemo { • public void printCount() { • try { for(int i = 5; i > 0; i--) { • System.out.println("Counter --- " + i ); } } • catch (Exception e) { • System.out.println("Thread interrupted."); } }} • class ThreadDemo extends Thread { • private Thread t; • private String threadName; • PrintDemo PD; • ThreadDemo( String name, PrintDemo pd) { • threadName = name; • PD = pd; } PROGRAMMING IN JAVA A. SIVASANKARI - SIASC-TVM
  • 17. PROGRAMMING IN JAVA • public void run() { • synchronized(PD) { • PD.printCount(); } • System.out.println("Thread " + threadName + " exiting."); } • public void start () { • System.out.println("Starting " + threadName ); • if (t == null) { • t = new Thread (this, threadName); • t.start (); } }} • public class TestThread { • public static void main(String args[]) { • PrintDemo PD = new PrintDemo(); • ThreadDemo T1 = new ThreadDemo( "Thread - 1 ", PD ); • ThreadDemo T2 = new ThreadDemo( "Thread - 2 ", PD ); • T1.start(); T2.start(); // wait for threads to end • try { T1.join(); T2.join(); } • catch ( Exception e) { • System.out.println("Interrupted"); } }} A. SIVASANKARI - SIASC-TVM
  • 18. PROGRAMMING IN JAVA This produces the same result every time you run this program OUTPUT • Starting Thread – 1 • Starting Thread – 2 • Counter --- 5 • Counter --- 4 • Counter --- 3 • Counter --- 2 • Counter --- 1 • Thread Thread - 1 exiting. • Counter --- 5 • Counter --- 4 • Counter --- 3 • Counter --- 2 • Counter --- 1 • Thread Thread - 2 exiting. A. SIVASANKARI - SIASC-TVM
  • 19. PROGRAMMING IN JAVA INTER-THREAD COMMUNICATION • Inter-thread communication or Co-operation is all about allowing synchronized threads to communicate with each other. Communication between threads is known is Inter-thread communication .If we are aware of interprocess communication then it will be easy for you to understand interthread communication. Interthread communication is important when you develop an application where two or more threads exchange some information. • Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed. There are three simple methods and a little trick which makes thread communication possible. All the three methods are listed below S.N Method & Description 1 public void wait()Causes the current thread to wait until another thread invokes the notify(). 2 public void notify()Wakes up a single thread that is waiting on this object's monitor. 3 public void notifyAll()Wakes up all the threads that called wait( ) on the same object. A. SIVASANKARI - SIASC-TVM
  • 20. PROGRAMMING IN JAVA EXAMPLE • class Chat { • boolean flag = false; • public synchronized void Question(String msg) • { if (flag) { • try { • wait(); } • catch (InterruptedException e) { • e.printStackTrace(); } } • System.out.println(msg); • flag = true; • notify(); } • public synchronized void Answer(String msg) • { if (!flag) { • try { • wait(); } • catch (InterruptedException e) { • e.printStackTrace(); } } • System.out.println(msg); A. SIVASANKARI - SIASC-TVM
  • 21. PROGRAMMING IN JAVA • flag = false; notify(); }} • class T1 implements Runnable { • Chat m; String[] s1 = { "Hi", "How are you ?", "I am also doing fine!" }; • public T1(Chat m1) { • this.m = m1; • new Thread(this, "Question").start(); } • public void run() { • for (int i = 0; i < s1.length; i++) { m.Question(s1[i]); } }} • class T2 implements Runnable { • Chat m; • String[] s2 = { "Hi", "I am good, what about you?", "Great!" }; • public T2(Chat m2) { • this.m = m2; • new Thread(this, "Answer").start(); } • public void run() { • for (int i = 0; i < s2.length; i++) { • m.Answer(s2[i]); } }} • public class TestThread { • public static void main(String[] args) { • Chat m = new Chat(); • new T1(m); • new T2(m); }}A. SIVASANKARI - SIASC-TVM
  • 22. PROGRAMMING IN JAVA • When the above program is complied and executed, it produces the following result OUTPUT • Hi • Hi • How are you ? • I am good, • what about you? • I am also doing fine! • Great! A. SIVASANKARI - SIASC-TVM
  • 23. PROGRAMMING IN JAVA DEADLOCK • Deadlock in java is a part of multithreading. Deadlock can occur in a situation when a thread is waiting for an object lock, that is acquired by another thread and second thread is waiting for an object lock that is acquired by first thread. Since, both threads are waiting for each other to release the lock, the condition is called deadlock. • Deadlock describes a situation where two or more threads are blocked forever, waiting for each other. Deadlock occurs when multiple threads need the same locks but obtain them in different order. A Java multithreaded program may suffer from the deadlock condition because the synchronized keyword causes the executing thread to block while waiting for the lock, or monitor, associated with the specified object. A. SIVASANKARI - SIASC-TVM
  • 24. A. SIVASANKARI - SIASC-TVM
  翻译: