0% found this document useful (0 votes)
19 views

Java

Uploaded by

rupaappili
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Java

Uploaded by

rupaappili
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

UNIT-III

MULTITHREADING

Creating threads:
Thread:
> A thread is a light wieght subprocess with the smallest unit of processes and also has separate
paths of execution. TPOINTIMG
>Threads are independent, if there occurs exception in one thread, it doesn't affect other
threads. It shares a common memory area.
>There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.
Thread class:
>provide constructors and methods to create and perform operations on a thread.
Commonly used Constructors of Thread class:

o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)
Commonly used methods of Thread class:
1. public void run(): iused to perform action for a thread.
2. public void start(): starts the execution of the thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to
sleep for the specified number of milliseconds.
4. public int getPriority(): returns the priority of the thread.
5. public int setPriority(int priority): changes the priority of the thread.
Runnable interface:
>should be implemented by any class
>have only one method named run().
Java Thread Example by extending Thread class
public void run(): is used to perform action for a thread.
class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}

Output:
thread is running...
INTERRUPTING THREADS:
>If any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the
interrupt() method on the thread, breaks out the sleeping or waiting state throwing
InterruptedException>Interrupt()method isused to interrupt the thread.
> If the thread is not in the sleeping or waiting state, calling the interrupt() method
performs normal behaviour and doesn't interrupt the thread
>The 3 methods provided by the Thread class for interrupting a thread
o public void interrupt()
o public static boolean interrupted()
o public boolean isInterrupted() DIADiagram

Example:
1. class TestInterruptingThread1 extends Thread{
2. public void run(){
3. try{
4. Thread.sleep(1000);
5. System.out.println("task");
6. }catch(InterruptedException e){
7. throw new RuntimeException("Thread interrupted..."+e); //Another prgm
8. }
9. }
10. public static void main(String args[]){
11. TestInterruptingThread1 t1=new TestInterruptingThread1();
12. t1.start();
13. try{
14. t1.interrupt();
15. }catch(Exception e){System.out.println("Exception handled "+e);}
16. }
17. }
Output:
Exception in thread-0
java.lang.RuntimeException: Thread interrupted...
java.lang.InterruptedException: sleep interrupted
at A.run(A.java:7)
Thread priorities:
>Each thread have a priority. Priorities are represented by a number between 1 and 10.
>In most cases, thread schedular schedules the threads according to their priority (known as
preemptive scheduling).
>Note that not only JVM a Java programmer can also assign the priorities of a thread explicitly.
Setter & Getter Method of Thread Priority:
public final int getPriority(): The java.lang.Thread.getPriority() method returns the
priority of the given thread.
public final void setPriority(int newPriority): The java.lang.Thread.setPriority() method
assign the priority of the thread.
3 constants defined in Thread class:
1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY
Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and
the value of MAX_PRIORITY is 10.
Example:
import java.lang.*; //// Importing the required classes
public class ThreadPriorityExample extends Thread
{
public void run()
{ // the print statement
System.out.println("Inside the run() method"); }
public static void main(String argvs[])
{ // Creating threads with the help of ThreadPriorityExample class
ThreadPriorityExample th1 = new ThreadPriorityExample();
ThreadPriorityExample th2 = new ThreadPriorityExample();
ThreadPriorityExample th3 = new ThreadPriorityExample();
System.out.println("Priority of the thread th1 is : " + th1.getPriority());
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
th1.setPriority(6);
th2.setPriority(3);
th3.setPriority(9);
System.out.println("Priority of the thread th1 is : " + th1.getPriority()); // 6
System.out.println("Priority of the thread th2 is : " + th2.getPriority()); // 3
System.out.println("Priority of the thread th3 is : " + th3.getPriority()); // 9
System.out.println("Currently Executing The Thread : " + Thread.currentThread().getName())
;
System.out.println("Priority of the main thread is : " + Thread.currentThread().getPrioriy());

// Priority of the main thread is 10 now Thread.currentThread().setPriority(10);


System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());

} }

Output:

Priority of the thread th1 is : 5


Priority of the thread th2 is : 5
Priority of the thread th2 is : 5
Priority of the thread th1 is : 6
Priority of the thread th2 is : 3
Priority of the thread th3 is : 9
Currently Executing The Thread : main
Priority of the main thread is : 5
Priority of the main thread is : 10
synchronizing threads:
> java supports multithreading. The problem of shared resources occurs when two or more
threads get execute at the same time.
>we need some way to ensure that the shared resource will be accessed by only one thread at a
time, and this is performed by using the concept called synchronization.
>The synchronization is the process of allowing only one thread to access a shared resource at a
time.
>Why use Synchronization?
The synchronization is mainly used to
1. To prevent thread interference.
2. To prevent consistency problem.
There are two types of synchronization:
1. Process Synchronization
2. Thread Synchronization
Thread Synchronization:
There are two types of thread synchronization mutual exclusive and inter-thread
communication.
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. Static synchronization.
2. Cooperation (Inter-thread communication in java)
Mutual Exclusive:
>Helps keep threads from interfering with one another while sharing data. It can be
achieved by using the following three ways:
1. By Using Synchronized Method
2. By Using Synchronized Block
3. By Using Static Synchronization
Synchronized method:
>When a method created using a synchronized keyword, it allows only one object to
access it at a time.
Synchronized block:
>The synchronized block is used when we want to synchronize only a specific sequence of
lines in a method.
DIA-btechsmart
Program:
class Table{
synchronized void printTable(int n){//synchronized method
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}}}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}}
public class TestSynchronization2{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
} } Output: 5
10
15
20
25
100
200
300
400
500
inter-thread communication(cooperation):
> Co-operation is all about allowing synchronized threads to communicate with each other.
>Inter-thread communication in Java 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.
>Java provides the following methods to achieve inter thread communication.
• wait( )
• notify( )
• notifyAll( )
1)wait() method:
>The wait() method causes current thread to release the lock and wait until
either another thread invokes the notify() method or the notifyAll() method for
this object.
2)notify() method:
>The notify() method wakes up a single thread that is waiting on this object's monitor. If
any threads are waiting on this object, one of them is chosen to be awakened.
Syntax:
1. public final void notify()
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor.
Syntax:
1. public final void notifyAll()
Understanding the process of inter-thread communication:

The point to point explanation of the above diagram is as follows


1. Threads enter to acquire lock.
2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the object. Otherwise it
releases the lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified state (runnable
state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits the monitor state of the
object.

You might also like