Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
9 views

Java Notes_Unit4_Multithreading - Google Docs

Uploaded by

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

Java Notes_Unit4_Multithreading - Google Docs

Uploaded by

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

‭ ultithreading‬

M ‭continue executing using notify() or notifyAll()‬


‭Java is a multi-threaded programming language which means we can develop multi‬ ‭3)‬‭sleeping(Timed Waiting) − A runnable thread can‬‭enter the timed waiting‬
‭threaded program using Java. A multi-threaded program contains two or more parts‬ ‭state for a specified interval of time. A thread in this state transitions back to the‬
‭that can run concurrently and each part can handle a different task at the same time‬ ‭runnable state when that time interval expires or when the event it is waiting for‬
‭making optimal use of the available resources specially when your computer has‬ ‭occurs.‬
‭multiple CPUs.‬ ‭5)‬‭Terminated (Dead) − A runnable thread enters the‬‭terminated state when‬
‭ hread:- Thread is a single flow of control within a program. We can also say that‬
T ‭it completes its task or otherwise terminates.‬
‭thread is a subprogram within a program.‬ ‭ hread Priorities‬
T
‭Multi-threading enables you to write in a way where multiple activities can proceed‬ ‭Every Java thread has a priority that helps the operating system determine the‬
‭concurrently in the same program.‬ ‭order in which threads are scheduled.‬
‭Life Cycle of a Thread:-‬ ‭Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and‬
‭A thread goes through various stages in its life cycle. For example, a thread is‬ ‭MAX_PRIORITY (a constant of 10). By default, every thread is given priority‬
‭born,‬‭started, runs, and then dies. The following‬‭diagram shows the complete life‬ ‭NORM_PRIORITY (a constant of 5).‬
‭cycle of a‬‭thread.‬ ‭Thread.MIN_PRIORITY(), Thread.NORM_PRIORITY(),‬
‭Thread.MAX_PRIORITY(),‬
‭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.‬
‭Create a Thread by Implementing a Runnable Interface‬‭If your‬
‭ lass is intended to be executed as a thread then you can achieve this by‬
c
‭implementing a Runnable interface. You will need to follow three basic steps −‬
‭Step 1: 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( )‬
‭Step 2:- As a second step, you will instantiate a Thread object using the following‬
‭constructor −‬
‭Following are the stages of the life cycle −‬ ‭Thread(Runnable threadObj, String threadName);‬
‭1)‬‭Newborn‬‭−‬‭A‬‭new‬‭thread‬‭begins‬‭its‬‭life‬‭cycle‬‭in‬‭the‬‭new‬‭state‬‭when‬‭is‬‭created‬ ‭Where, threadObj is an instance of a class that implements the Runnable interface‬
‭ sing‬‭new‬‭keyword.‬‭It‬‭remains‬‭in‬‭this‬‭state‬‭until‬‭the‬‭program‬‭starts‬‭the‬‭thread.‬‭It‬
u ‭and threadName is the name given to the new thread.‬
‭is also referred to as a born thread.‬ ‭Step 3:- Once a Thread object is created, you can start it by calling start() method,‬
‭2)‬‭Runnable − After a newly born thread is started,‬‭the thread becomes runnable.‬ ‭which executes a call to run( ) method. Following is a simple syntax of start() method‬
‭A thread in this state is waiting for CPU timing.‬ ‭–‬
‭3)‬‭Running:-After runnable state when run() gets called,‬‭thread goes into‬ ‭void start();‬
‭running mode.In this satate thread is actually executing its task.‬
‭4)‬‭Blocked: −Thread goes into blocked state either‬‭of the following situation as‬ ‭Example‬
‭shown in above diagram‬ ‭ ere is an example that creates a new thread and starts running it −‬
H
‭1)‬‭Either thread is suspended. Thread is again gets‬‭the CPU timing by‬
‭calling resume().‬ ‭class RunnableDemo implements Runnable {‬
‭2)‬‭waiting: Sometimes, a thread transitions to the‬‭waiting state while the‬ ‭private Thread t;‬
‭thread waits for another thread to perform a task. A thread transitions back to‬ ‭private String threadName;‬
‭the runnable state only when another thread signals the waiting thread to‬
‭ Thread: Thread‬
2
‭RunnableDemo( String name) {‬ ‭2, 4‬
‭threadName = name;‬ ‭Thread: Thread-1, 3‬
‭System.out.println("Creating " + threadName );‬ ‭Thread: Thread-2, 3‬
‭}‬ ‭Thread: Thread-1, 2‬
‭Thread: Thread-2, 2‬
‭public void run() {‬ ‭Thread: Thread-1, 1‬
‭System.out.println("Running " + threadName‬ ‭Thread: Thread-2, 1‬
‭); try {‬ ‭Thread Thread-1 exiting.‬
‭for(int i = 4; i > 0; i--) {‬ ‭Thread Thread-2 exiting.‬
‭System.out.println("Thread: " + threadName + ", " + i);‬ ‭Create a Thread by Extending a Thread Class‬
‭// Let the thread sleep for a while.‬ ‭ he second way to create a thread is to create a new class that extends Thread class‬
T
‭Thread.sleep(50);‬ ‭using the following two simple steps. This approach provides more flexibility in‬
‭}‬ ‭handling multiple threads created using available methods in Thread class. Step 1:-‬
‭}catch (InterruptedException e) {‬ ‭You will need to override run( ) method available in Thread class. This method‬
‭System.out.println("Thread " + threadName + " interrupted.");‬ ‭provides an entry point for the thread and you will put your complete business logic‬
}‭ ‬ ‭inside this method. Following is a simple syntax of run() method − public void run( )‬
‭System.out.println("Thread " + threadName + " exiting.");‬ ‭Step 2:- Once 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‬
‭public void start () {‬ ‭–‬
‭System.out.println("Starting " + threadName );‬ ‭ oid start( );‬
v
‭if (t == null) {‬ ‭Example‬
‭t = new Thread (this, threadName);‬ ‭Here is the preceding program rewritten to extend the Thread −‬
‭t.start ();‬ ‭class ThreadDemo extends Thread {‬
‭} }‬ ‭private Thread t;‬
}‭ ‬ ‭private String threadName;‬
‭public class TestThread {‬ ‭ThreadDemo( String name) {‬
‭public static void main(String args[]) {‬ ‭threadName = name;‬
‭RunnableDemo R1 = new RunnableDemo( "Thread-1");‬ ‭System.out.println("Creating " + threadName );‬
‭R1.start();‬ ‭}‬
‭RunnableDemo R2 = new RunnableDemo( "Thread-2");‬ ‭public void run() {‬
‭R2.start();‬ ‭System.out.println("Running " + threadName‬
‭} }‬ ‭); try {‬
‭ his will produce the following result −‬
T ‭for(int i = 4; i > 0; i--) {‬
‭Output‬ ‭System.out.println("Thread: " + threadName + ", " + i);‬
‭ reating Thread-1‬
C ‭// Let the thread sleep for a while.‬
‭Starting Thread-1‬ ‭Thread.sleep(50);‬
‭Creating Thread-2‬ ‭}‬
‭Starting Thread-2‬ ‭}catch (InterruptedException e) {‬
‭Running Thread-1‬ ‭System.out.println("Thread " + threadName + " interrupted.");‬‭}‬
‭Thread: Thread-1,‬ ‭System.out.println("Thread " + threadName + " exiting.");‬‭}‬
‭4 Running Thread‬
‭ oid setPriority(int priority):-‬‭Sets the priority of this Thread object. The possible‬
v
‭public void start () {‬ ‭values are between 1 and 10.‬
‭System.out.println("Starting " + threadName );‬ ‭5)‬‭public final void setDaemon(boolean on):‬‭-A parameter‬‭of true denotes‬

‭if (t == null) {‬ ‭this Thread as a daemon thread.‬


‭6)‬‭public final void join(long millisec):-‬‭The current‬‭thread invokes this method‬
‭t = new Thread (this, threadName);‬
‭on a second thread, causing the current thread to block until the second thread‬
‭t.start ();‬
‭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.‬
‭public class TestThread {‬
‭8)‬‭public final boolean isAlive():‬‭-Returns true if‬‭the thread is alive, which is‬
‭public static void main(String args[]) {‬ ‭any time after the thread has been started but before it runs to completion.‬
‭ThreadDemo T1 = new ThreadDemo( "Thread‬
‭1"); T1.start();‬ ‭ he previous methods are invoked on a particular Thread object. The following‬
T
‭ hreadDemo T2 = new ThreadDemo( "Thread-2");‬
T ‭methods in the Thread class are static. Invoking one of the static methods‬
‭ 2.start();‬
T ‭performs the operation on the currently running thread.‬
‭}‬ ‭1)‬‭public static void yield():‬‭- Causes the currently‬‭running thread to yield to any‬
}‭ ‬ ‭ ther threads of the same priority that are waiting to be scheduled.‬‭2)‬‭public‬
o
‭This will produce the following result −‬ ‭static void sleep(long millisec):‬‭- Causes the currently‬‭running thread to block‬
‭Output‬ ‭for at least the specified number of milliseconds.‬
‭ reating Thread-1‬
C ‭3)‬‭public static boolean holdsLock(Object x):‬‭- Returns‬‭true if the current‬
‭Starting Thread-1‬ ‭thread holds the lock on the given Object.‬
‭Creating Thread-2‬ ‭4)‬‭public static Thread currentThread():‬‭- Returns‬‭a reference to the‬

‭Starting Thread-2‬ ‭currently running thread, which is the thread that invokes this method.‬‭5)‬
‭Running Thread-1‬ ‭public static void dumpStack():‬‭- Prints the stack‬‭trace for the currently‬
‭Thread: Thread-1,‬ ‭running thread, which is useful when debugging a multithreaded application.‬
‭4 Running Thread‬
‭2 Thread: Thread‬ ‭Example‬
‭2, 4‬ ‭ he following ThreadClassDemo program demonstrates some of these methods‬
T
‭Thread: Thread-1, 3‬ ‭of the Thread class. Consider a class DisplayMessage which implements‬
‭Thread: Thread-2, 3‬ ‭Runnable −‬
‭Thread: Thread-1, 2‬ ‭// Create a thread to implement Runnable‬
‭Thread: Thread-2, 2‬ ‭public class DisplayMessage implements Runnable {‬
‭Thread: Thread-1, 1‬ ‭private String message;‬
‭public DisplayMessage(String message) {‬
‭Thread: Thread-2, 1‬
‭this.message = message;‬
‭Thread Thread-1 exiting.‬
‭}‬
‭Thread Thread-2 exiting.‬
‭public void run() {‬
‭Thread Methods‬
‭while(true) {‬
‭Following is the list of important methods available in the Thread class.‬
‭1)‬‭public void start():‬‭- Starts the thread in a separate‬‭path of execution, then‬
‭System.out.println(message);‬
‭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.‬ ‭// Create a thread to extentd Thread‬
‭3)‬‭public final void setName(String name):-‬‭Changes‬‭the name of the Thread‬ ‭public class GuessANumber extends Thread‬
‭object. There is also a getName() method for retrieving the name.‬‭4)‬‭public final‬ ‭{‬‭private int number;‬
‭public GuessANumber(int number) {‬ ‭ ystem.out.println("main() is‬
S
‭this.number = number;‬ ‭ending...");‬
‭}‬ ‭}‬
‭public void run() {‬ }‭ ‬
‭int counter = 0;‬ ‭This will produce the following result. You can try this example again and again‬
‭int guess = 0;‬ ‭and you will get a different result every time.‬
‭do {‬ ‭Output‬
‭guess = (int) (Math.random() * 100 + 1);‬ ‭Starting hello thread...‬
‭System.out.println(this.getName() + " guesses " + guess);‬ ‭Starting goodbye thread...‬
‭counter++;‬ ‭Hello‬
‭} while(guess != number);‬ ‭Hello‬
‭System.out.println("** Correct!" + this.getName() + "in" + counter + "guesses.**");‬ ‭Hello‬
‭}‬ ‭Hello‬
}‭ ‬ ‭Hello‬
‭Following is the main program, which makes use of the above-defined classes −‬ ‭Hello‬
‭public class ThreadClassDemo {‬ ‭Goodby‬
‭public static void main(String [] args) {‬ ‭e‬
‭Runnable hello = new DisplayMessage("Hello");‬ ‭Goodby‬
‭Thread thread1 = new Thread(hello);‬ ‭e‬
‭thread1.setDaemon(true);‬ ‭Goodby‬
‭thread1.setName("hello");‬ ‭‬
e
‭System.out.println("Starting hello thread...");‬ ‭Goodby‬
‭thread1.start();‬ ‭e‬
‭Goodby‬
‭ unnable bye = new‬
R ‭e‬
‭DisplayMessage("Goodbye"); Thread thread2 =‬ ‭......‬
‭new Thread(bye);‬
‭thread2.setPriority(Thread.MIN_PRIORITY);‬ I‭nter-thread communication in Java‬
‭thread2.setDaemon(true);‬ ‭Inter-thread communication or Co-operation is all about allowing synchronized‬
‭System.out.println("Starting goodbye thread...");‬ ‭threads to communicate with each other.‬
‭thread2.start();‬ ‭Cooperation (Inter-thread communication) is a mechanism in which a thread is‬
‭System.out.println("Starting thread3...");‬ ‭paused running in its critical section and another thread is allowed to enter (or‬
‭Thread thread3 = new‬ ‭lock) in the same critical section to be executed.It is implemented by following‬
‭GuessANumber(27); thread3.start();‬ ‭methods of Object class:‬
‭try {‬ ‭wait() notify()‬
‭thread3.join();‬ ‭notifyAll()‬
‭}catch(InterruptedException e) {‬ ‭1)‬‭wait() method:- Causes current thread to release‬‭the lock and wait until either‬
‭System.out.println("Thread interrupted.");‬ ‭another thread invokes the notify() method or the notifyAll() method for this object,‬
‭}‬ ‭or a specified amount of time has elapsed.‬
‭System.out.println("Starting thread4...");‬ ‭The current thread must own this object's monitor, so it must be called from the‬
‭Thread thread4 = new‬ ‭synchronized method only otherwise it will throw exception.‬
‭GuessANumber(75);‬ ‭public final void wait()throws InterruptedException waits until object is notified.‬
‭thread4.start();‬ ‭public final void wait(long timeout)throws InterruptedException waits for the‬
‭specified amount of time.‬ ‭ yThread t1=new MyThread();‬
M
‭2)‬‭notify() method- Wakes up a single thread that‬‭is waiting on this object's‬ ‭MyThread t2=new MyThread();‬
‭monitor. If any threads are waiting on this object, one of them is chosen to be‬ ‭t1.start();‬
‭awakened. The choice is arbitrary and occurs at the discretion of the‬ ‭t2.start();‬
‭implementation.‬ ‭System.out.println(t1.isAlive());‬
‭Syntax:‬ ‭System.out.println(t2.isAlive());‬
‭public final void notify()‬ ‭}‬
‭3)‬‭notifyAll() method:- Wakes up all threads that‬‭are waiting on this object's‬ }‭ ‬
‭monitor. Syntax:‬ ‭Output :‬
‭public final void notifyAll()‬
‭r1‬
‭ oining threads‬
J
t‭rue‬
‭Sometimes‬ ‭one‬ ‭thread‬ ‭needs‬ ‭to‬ ‭know‬ ‭when‬ ‭other‬ ‭thread‬ ‭is‬ ‭terminating.‬ ‭In‬
‭true‬
‭java,‬ ‭isAlive()‬ ‭and‬ ‭join()‬ ‭are‬ ‭two‬ ‭different‬ ‭methods‬ ‭that‬ ‭are‬ ‭used‬ ‭to‬ ‭check‬
‭r1‬
‭whether a thread has finished its execution or not.‬
‭r2‬
‭ he isAlive() method returns true if the thread upon which it is called is still running‬
T
‭r2‬
‭otherwise it returns false.‬
‭Example of thread without join() method‬
‭final boolean isAlive()‬
‭But, join() method is used more commonly than isAlive(). This method waits until‬
‭ ublic class MyThread extends Thread‬
p
‭the thread on which it is called terminates.‬
‭{‬
‭final void join() throws InterruptedException‬
‭public void run()‬
‭Using join() method, we tell our thread to wait until the specified thread completes‬
‭{‬
‭its execution. There are overloaded versions of join() method, which allows us to‬
‭specify time for which you want to wait for the specified thread to terminate. final‬ ‭System.out.println("r1 ");‬
‭void join(long milliseconds) throws InterruptedException‬ ‭try {‬
‭As we have seen in the Introduction to MultiThreading, the main thread must‬ ‭Thread.sleep(500);‬
‭always be the last thread to finish its execution. Therefore, we can use Thread‬ ‭}‬
‭join() method to ensure that all the threads created by the program has been‬ ‭catch(InterruptedException ie){ }‬
‭terminated before the execution of the main thread.‬ ‭System.out.println("r2 ");‬
‭}‬
‭Example of isAlive method‬ ‭public static void main(String[] args)‬
‭ ublic class MyThread extends Thread‬
p ‭{‬
‭{‬ ‭MyThread t1=new MyThread();‬
‭public void run()‬ ‭MyThread t2=new MyThread();‬
‭{‬ ‭t1.start();‬
‭System.out.println("r1 ");‬ ‭t2.start();‬
‭try {‬ ‭}‬
‭Thread.sleep(500);‬ ‭}‬
‭}‬ ‭Output :‬
‭catch(InterruptedException ie) { }‬ ‭r1‬
‭System.out.println("r2 ");‬ ‭r1‬
‭}‬ ‭r2‬
‭public static void main(String[] args)‬ ‭r2‬
‭{‬ ‭In this above program two thread t1 and t2 are created. t1 starts first and after‬
‭ rinting "r1" on console thread t1 goes to sleep for 500 ms. At the same time‬
p
‭1.‬‭Synchronized method.‬
‭Thread t2 will start its process and print "r1" on console and then go into sleep for‬
‭500 ms. Thread t1 will wake up from sleep and print "r2" on console similarly‬ ‭2.‬‭Synchronized‬‭block.‬
‭thread t2 will wake up from sleep and print "r2" on console. So you will get output‬ ‭3.‬‭static synchronization.‬
‭like r1 r1 r2 r2 Example of thread with join() method‬
‭2.‬‭Cooperation (Inter-thread communication in java)‬
‭public class MyThread extends Thread‬
‭{‬
‭Mutual Exclusive‬
‭public void run()‬
‭ utual Exclusive helps keep threads from interfering with one another while sharing‬
M
‭{‬ ‭data. This can be done by three ways in java:‬
‭System.out.println("r1 ");‬
‭try {‬ ‭1.‬‭by synchronized method‬
‭Thread.sleep(500);‬
‭2.‬‭by synchronized block‬
‭}catch(InterruptedException ie){ }‬
‭System.out.println("r2 ");‬ ‭3.‬‭by static synchronization‬
‭}‬
‭public static void main(String[] args)‬ ‭Concept of Lock in Java‬
‭{‬
‭ ynchronization is built around an internal entity known as the lock or monitor.‬
S
‭MyThread t1=new MyThread();‬ ‭Every object has an lock associated with it. By convention, a thread that needs‬
‭MyThread t2=new MyThread();‬ ‭consistent access to an object's fields has to acquire the object's lock before‬
‭t1.start();‬ ‭accessing them, and then release the lock when it's done with them.‬
‭try{‬
‭t1.join(); //Waiting for t1 to finish‬ ‭Java synchronized method‬
‭}catch(InterruptedException ie){}‬
‭If you declare any method as synchronized, it is known as synchronized method.‬
‭t2.start();‬
‭} }‬ ‭Synchronized method is used to lock an object for any shared resource.‬
‭Output :‬
‭r1‬ ‭ hen a thread invokes a synchronized method, it automatically acquires the lock for‬
W
‭r2‬ ‭that object and releases it when the thread completes its task.‬
‭r1‬
‭r2‬ ‭Synchronized Block in Java‬
‭In this above program join() method on thread t1 ensures that t1 finishes it process‬
‭ ynchronized block can be used to perform synchronization on any specific‬
S
‭before thread t2 starts.‬
‭resource of the method.‬
‭Specifying time with join()‬
‭If in the above program, we specify time while using join() with t1, then t1 will‬ ‭ uppose you have 50 lines of code in your method, but you want to synchronize‬
S
‭execute for that time, and then t2 will join it.‬ ‭only 5 lines, you can use synchronized block.‬
‭t1.join(1500);‬
‭If you put all the codes of the method in the synchronized block, it will work same as‬
‭Doing so, initially t1 will execute for 1.5 seconds, after which t2 will join it.‬ t‭he synchronized method.‬

‭Thread synchronization:-‬ *‭ **Refer the example of thread synchronization shared on google‬


‭classroom.‬
‭ here are two types of thread synchronization mutual exclusive and inter-thread‬
T
‭communication.‬

‭1.‬‭Mutual Exclusive‬

You might also like