Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
25 views
Java
It is very useful for you
Uploaded by
zuwairiyamariyam2305
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save Java For Later
Download
Save
Save Java For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
25 views
Java
It is very useful for you
Uploaded by
zuwairiyamariyam2305
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save Java For Later
Carousel Previous
Carousel Next
Save
Save Java For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 9
Search
Fullscreen
3.10: Thread Synchronization [ Definition: ThreadSynchronation SSS ‘Thread synchronization is the concurrent execution of two or more threads that share critical resources. | When two or more threads need t9 use a shared resource, they need some way to | ensure that the-tesource will betsed by only one thread at a time. The process of | ensuring single thread access toa shared resource ata time is called synchronization. ‘Threads Should be synchronized to avoid critical resource use conflicts. Otherwise, conflicts may arise when parallel-running threads attempt to modify a common variable atthe same time. Y Whyuse Synchronization ‘The synchronization is mainly used to 1. To preventthread interference, 2. Toprevent consistency problem, ¥ ‘Thread Synchronization ‘There are two types of thread synchronization mutual exclusive and inter-thread communication 1. Mutual Exclusive 1. Synchronized method. 2. Synchronized block. (53391 ~ Object Oriented Programming ~Il Sem CSE u DOWNLOADED FROM STUCOR APP Department of CSE. 3, statle synchronization, 2. Cooperation (Inter-thread communication in java) Y Mutual Exclusive Mutual Exclusive helps keep threads from interfering with one another while sharing data, This can be done by two ways in java 1. by synchronized method 2. bysynchronized block ¥ Concept of Lock in Java Synchronization is built around an internal entity known as the lock or monitor. Every object has a lock associated with i. By convention, a thread that needs consistent access to an object's fields has to acquire the object's lock before accessing them, and then release the lock when it's done with them. 1. Javasynchronized method ¥ If you declare any method as synchronized; itis known’ as synchronized method. ‘Synchronized method is used to lock an object for any shared resource. When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases It when the thread completes its task. mtaxtouse: iz ‘Access, modifier synchronized return type method _name(parameters) mel, ‘Example of java synchronized method: class Table{ synchronized void printTable(int n)//synchronized method i for(int it;ke=5il+4) ( systemoutprintin(a); ty Threadsleep(400); catch(Exception ¢){System.outprintin(e); } ) ) }class MyThread1 extends Thread { Table t; MyThread1(Table t){ this.t=t; public void run(){ tprintTable(5); } ae class MyThread2 extends Thread{ Table t; MyThread2(Table t){ this.t=t; } public void runQ{ tprintTable(100); ' d public class TestSynchronization2{ public static void main(String args{]){ Table obj = new Table();_ //only one object MyThread1 tl=new MyThread1(obj); MyThread2 t2=new MyThread2(obj); tLstartQ; t2,startQ; tt Output: 5 10 15 20 25 100 200 300 400 5002. Synchronized block in java Y Synchronized block can be used to perform synchronization on any specific resource of the method. ¥ Suppose you have 50 lines of code in your method, but you want to synchronize only 5 lines, you can use synchronized block. ¥ Ifyou put all the codes of the method in the synchronized block, it will work same as the synchronized method. Points to remember for Synchronized block + Synchronized block is used to lock an object for any shared resource. + Scope of synchronized block is smaller than the method. Syntax to use synchronized block 1. synchronized (object reference expression) { 2. //code block 3.) Example of synchronized block class Table void printTable(int n) { synchronized(this) //synchronized block { forint i=1;i<=5;i+4){ System.out printin(n*i); try{ Threadsleep(400); _}catch(Exception e){System.out-printin(e);} } } }/fend of the method } class MyThread1 extends Thread{ Table t; MyThread1 (Table t)( this.t=t; } public void run(){ tprintTable(5);} class MyThread2 extends Thread{ Table t; MyThread2(Table t){ thist=t; } public void run(){ tprineTable(100); } } public class TestSynchronizedBlock1 { public static void main(String args{]) { ‘Table obj = new Table();//only one object MyThread1 t1=new MyThread1(obj); MyThread2 t2=new MyThread2(obj); t1.startQ; t2start(}; } } Output: 10 15 20 25 100 200 300 400 500Definition: Thread A thread is a lightweight sub-process that defines a separate path of execution. It is the smallest unit of processing that can run concurrently with the other parts (other threads) of the same process. Y¥ Threads are independent. v If there occurs exception in one thread, it doesn't affect other threads. v Itusesa shared memory area. os ¥ Asshown inthe above figure, a thread is executed inside the process. v There is context-switching between the threads. Y There can be multiple processes inside the 0S, and one process can have multiple threads.‘A program can be divided into a number of small processes. Each small process can be addressed asa single thread. [Definition:Mulitheeading Multithreading isa technique of executing moré than one thread, performing different tasks, simultaneously Multithreading enables programs to have more than one execution paths which executes concurrently. Each such execution path fs a thread. For example, one thread is writing content(on a file at the same time another thread Is performing spelling, check. ‘Advantages of Threads/ Multithreading: 1. Threads are light weight compared to processes. 2, Threads share the same address space and therefore can share both data and code. Context switching between threads is usually less expensive that between processes Cost of thread communication fs low than inter-process communication, ‘Threads allow different tasks to be performed concurrently. Reduces the computation time, ‘Through multithreading, efficient utlization of system resources can be achieved, ‘MULTITASKING Multitasking is a process of executing multiple tasks simultane ‘multitasking to maximize the utilization of CPU. sly. We use 53391 ~ Object Oriented Programming ~ Sem CSE 2 DOWNLOADED FROM STUCOR APP Department of CSE. “Multitasking can be achieved in two ways: 1) Process-based Multitasking (Multipracessing):- ‘© It isa feature of executing two or more programs concurrently. ® For example, process-based multitasking enables you to run the Java compiler at the same time that you are using.a text editor or visiting a web site, 2) Thread-based Multitasking (Multithreading):- ‘ It is a feature that a single program can perform two or more tasks simultaneously. “+ For instance, a text editor can format text atthe same time that it is printing, as long.as these two actions are being performed by two separate threads, Differences between mult-threading and multitasking Characteristics Multithreading Multitasking ‘Meaning ‘A process is divided into several | The execution of more than one different sub-processes called as | task simultaneously Is called as threads, which has its own path | mulekasking. of execution. This concept is called as multithreading. Number of CPU | Canbe one or morethanone | One ‘Number of. Various components of the same | One by one jobis being processbeing _| processarebeing executed ata | executed ata time. executed time, Number ofusers | Usually one. More than one, ‘Memory Space | Threads are lighter weight. They | Processes are heavyweight share the same address space | tasks that require their own separate address spaces. ‘Communication | Interthread communication Is | Interprocess communication f= between units | inexpensive ‘expensive and limited Context Switching | Context switching fromone | Context switching from one thread tothe next is lower in| process to another is also costly,What is exception handling? Exception Handling Isa mechanism to handle runtime errors, such as ‘ClassNotFoundException, IOException, SQLException, RemoteException et. by taking the necessary actions, 0 that normal law ofthe aplication ca be maintained. ‘Advantage ofusing Exceptions: Maintains the normal low of execution ofthe application. Exceptions separate error handling cde from regula code ‘Benefit Cleaner lgoethms, less cuter Meaningful Error reporting Exception standardize errr handling JAVA EXCEPTION HANDLING KEYWORDS Exception Handling in java fs managed using the lowing five keywords [SNe] Keyword | Description try | Avlockofzodethatis wie monitored for exception. ~~ Phe catch bloc handles the specie type of exception along catch | with the try block. For each corresponding ty block there exists the catch block Te species the cove that must be executed even Tough exception mayor may not ocr. This keyword is used wo expitiy throw specie exeption Fom the program coe, Te species the exceptions that Gan Be thrown by a parear method ‘nally The java code that might throw an exception i enclosed in try block. It must be used within the method and must be followed by either catch or finally block. €s3381~ Object vented Programing Semester CSE ut DOWNLOADED FROM STUCOR APP Depanmest of CSE © ‘fan exception is generated within the ty black, the remaining statementsin the try bck are not executed > catchBlod: 17 Exceptions thrown during execution of the try black can be caught and handled in a cate block, + On exit from a catch block, normal execution continwes and the fray block is execute. > ‘final Blocks ‘finally block salways executed, regardless ofthe cause of ext rom the ty block oF whether any catch block was executed ¥ Generally finally block is used for freeing resources, cleaning up, closing Even though there fs any exception in the ty block, the statemiénts assured by finally block are sure to execute v Rule: «+ For exch try block there can be zero or more catch blocks, but only one finally block. + The finally block will not be exceuted if program eaits(elther by calling System.ext() or by causing a fatal error that causes the process to abort) ‘The sry-catehSnally structure Senta): wy I) Code beck 1 ‘atch (BecoptonTypet et) 1/Mandle Exception ype exceptions ) ‘atch (BecoptonType2 e2) ( 1/ Handle ExceptionType2 exceptions ) is Analy ( 1/ Codealways executed attr the Jy aa any catch block )ules for ry. catchand nally Block: 1] Statements that might anerte am exception are placed ina ty block 2} otal statements in thet Slack wl ence the encom i interrupted Man 3) For each ry back there canbe sero ar more catch acs but ony one Ally 4) The uy boc allowed by \oneor more catch Backs 5) Atryboce max befllowodby ether at am one cateh block or on aly lock. 6) cates Bleck species the spe of exception Fe an catch. Ie contin he code ‘known a exception handler 17) Tho catch leks aod al Hock must always appear In conjunction with ary block 4) The order of exception handlers nthe catch block must be fom the mob spec rneramthout Exception handing: (Default excetion handler: slat Spe ‘ pub wat wo maining ors ‘ Inc atass070; Systemovtipringh resto the code.” xcepton In thread mat javalang ArthmetlcEsception/ by aro de ttetenti ot priatd, Program Explanation: ‘The VM frty checks whether the exception is handled oF ot exception is not andes VM provides default exertion ander te performs the following aks Prints ouceacepton desertion. 1 Printsthe stack race (Herarchy of methods where the exception acurred), ia 1 econ Ome je eattne sie econ faerie sample: publics Demo t ube tte void maining ars) ‘ ey in daa 25/0; Systemot pita ) ee Arthmedieicepion) 1 ‘Shmtemautprint(e) p aly ‘Sytemoutprindo( rally back sawayserecuted; ? Systemautprin rest ofthe code"): Arithmetcbxception: / by eroNo exceptions thrown: wy co ? CAKENL ron) — , co + hoxtline of the code An exception arises : ext line of the code
You might also like
Multithreading: The Java Thread Model
PDF
No ratings yet
Multithreading: The Java Thread Model
15 pages
Exception Handling, Mutithreading
PDF
No ratings yet
Exception Handling, Mutithreading
6 pages
Multitheading in Java
PDF
No ratings yet
Multitheading in Java
18 pages
chavan CH-4.2
PDF
No ratings yet
chavan CH-4.2
75 pages
Presentation On:: Multi-Threading and Thread Synchronization
PDF
No ratings yet
Presentation On:: Multi-Threading and Thread Synchronization
24 pages
MultiThreadedProgramming
PDF
No ratings yet
MultiThreadedProgramming
37 pages
Multithread and Synchronization
PDF
No ratings yet
Multithread and Synchronization
27 pages
Chapter 5
PDF
No ratings yet
Chapter 5
18 pages
Unit -II- FSD
PDF
No ratings yet
Unit -II- FSD
24 pages
Computer Science Unit 4
PDF
No ratings yet
Computer Science Unit 4
7 pages
Multithreading in Java
PDF
No ratings yet
Multithreading in Java
9 pages
Java Unit 4
PDF
No ratings yet
Java Unit 4
53 pages
Java Muti Threading
PDF
No ratings yet
Java Muti Threading
12 pages
Java Programming UNIT-4: Thread
PDF
No ratings yet
Java Programming UNIT-4: Thread
22 pages
Java Programming UNIT-4: Thread
PDF
No ratings yet
Java Programming UNIT-4: Thread
22 pages
Threads
PDF
No ratings yet
Threads
46 pages
U03 Multi Threading
PDF
No ratings yet
U03 Multi Threading
24 pages
CH 1
PDF
No ratings yet
CH 1
26 pages
Part - B Unit - 4 Multithreading and Generic Programming
PDF
No ratings yet
Part - B Unit - 4 Multithreading and Generic Programming
11 pages
Java Iii
PDF
No ratings yet
Java Iii
32 pages
Exception Handling
PDF
No ratings yet
Exception Handling
6 pages
Threads Synchronization
PDF
No ratings yet
Threads Synchronization
29 pages
Threads in Java
PDF
No ratings yet
Threads in Java
23 pages
CS8392 - OOPs - UNIT - 4 - PPT - 4.1
PDF
No ratings yet
CS8392 - OOPs - UNIT - 4 - PPT - 4.1
76 pages
Multithreading Interview Questions: Click Here
PDF
No ratings yet
Multithreading Interview Questions: Click Here
37 pages
Multithreading in Java
PDF
No ratings yet
Multithreading in Java
5 pages
Ooc Module 4
PDF
No ratings yet
Ooc Module 4
13 pages
Java Multithreading PDF
PDF
No ratings yet
Java Multithreading PDF
1 page
Oops Through Java Unit IV
PDF
No ratings yet
Oops Through Java Unit IV
8 pages
Java Unit-3 Student
PDF
No ratings yet
Java Unit-3 Student
92 pages
Lab 11
PDF
No ratings yet
Lab 11
12 pages
UNIT 3 QB Oops
PDF
No ratings yet
UNIT 3 QB Oops
6 pages
Java Unit - 5 Notes
PDF
No ratings yet
Java Unit - 5 Notes
33 pages
Java Threads & Synchronization
PDF
No ratings yet
Java Threads & Synchronization
47 pages
EContent_11_2025_04_17_11_57_44_Unit_6_Multithreadingpptx__2025_04_09_13_10_13
PDF
No ratings yet
EContent_11_2025_04_17_11_57_44_Unit_6_Multithreadingpptx__2025_04_09_13_10_13
30 pages
Chapter 6-7
PDF
No ratings yet
Chapter 6-7
15 pages
Java Multithreading
PDF
No ratings yet
Java Multithreading
23 pages
Unit 4_LMS
PDF
No ratings yet
Unit 4_LMS
43 pages
Chapter 7 Multithreading Programming PDF
PDF
No ratings yet
Chapter 7 Multithreading Programming PDF
64 pages
java_oops
PDF
No ratings yet
java_oops
50 pages
Multitasking and Concurrency
PDF
No ratings yet
Multitasking and Concurrency
13 pages
CS8392 - OOPs - UNIT - 4 - PPT - 4.1
PDF
No ratings yet
CS8392 - OOPs - UNIT - 4 - PPT - 4.1
76 pages
Java programming notes
PDF
No ratings yet
Java programming notes
31 pages
Multithreading in Java
PDF
No ratings yet
Multithreading in Java
19 pages
Java Unit 4
PDF
No ratings yet
Java Unit 4
39 pages
Unit - 4: Multithreading
PDF
No ratings yet
Unit - 4: Multithreading
15 pages
Unit 3 App
PDF
No ratings yet
Unit 3 App
36 pages
26-Synchronization in Java
PDF
No ratings yet
26-Synchronization in Java
12 pages
MultiThreading and Synchronization
PDF
No ratings yet
MultiThreading and Synchronization
43 pages
Module Vi Oops 1
PDF
No ratings yet
Module Vi Oops 1
29 pages
Multi Threading
PDF
No ratings yet
Multi Threading
2 pages
OOPS U4
PDF
No ratings yet
OOPS U4
44 pages
Unit 3 Notes
PDF
No ratings yet
Unit 3 Notes
36 pages
Multithreading and Exception Handling
PDF
No ratings yet
Multithreading and Exception Handling
40 pages
Multi Threading
PDF
No ratings yet
Multi Threading
33 pages
Multithreading in Java
PDF
No ratings yet
Multithreading in Java
10 pages
Concept of Threads in Java
PDF
No ratings yet
Concept of Threads in Java
6 pages
Javatpoint Multithreading
PDF
No ratings yet
Javatpoint Multithreading
16 pages
OOPS UNIT 3 Two Marks
PDF
No ratings yet
OOPS UNIT 3 Two Marks
5 pages