Multithreading Class Notes Java
Multithreading Class Notes Java
scheduler
always chooses
the thread for
execution only if
it is already in
the RUNNABLE
state.
How to create a thread in Java
2 Methods It has multiple methods including It has only abstract method run()
start() and run()
Thread t;
NewThread(String threadname) {
name = threadname;
output Three: 2
Two: 2
One: 1
Three: 1
Two: 1
One exiting.
Two exiting.
Three exiting.
Main thread exiting.
Synchronization
• When two or more threads need access to a shared resource,
they need some way to ensure that the resource will be used
by only one thread at a time. The process by which this is
achieved is called synchronization.
• Key to synchronization is Monitor also called as semaphore
• A monitor is an object that is used as a mutually exclusive
lock, or mutex. Only one thread can own a monitor at a given
time.
• The program without synchronization is
package com.mycompany.example;
class Table{
void print(int val){
for(int i=1;i<=10;i++){
System.out.println(val*i);
try{
Thread.sleep(1000);
}catch(Exception e){
System.out.println(e);
}
}
}
}
class Thread1 extends Thread{ class Thread2 extends Thread{
Table t; Table t;
Thread1(Table t){ Thread2(Table t){
this.t=t; this.t=t;
} }
public void run(){ public void run(){
t.print(4); t.print(6);
} }
} }
public class Example
t1.start();
t2.start();
}
Output:
6
4
24
8
42
12
28
12
48
18
32
24
54
16
36
30
60
20
40
36
class Table{
synchronized void print(int 4 6
val){ 8 12
for(int i=1;i<=10;i++){ 12 18
System.out.println(val*i); 16 24
20 30
try{
24 36
Thread.sleep(1000); 28 42
}catch(Exception e){ 32 48
System.out.println(e); 36 54
40 60
}
}
}
}
The synchronized Statement
• While creating synchronized methods within classes
that you create is an easy and effective means of
achieving synchronization, it will not work in all cases.
• To understand why, consider the following.
• Imagine that you want to synchronize access to objects
of a class that was not designed for multithreaded
access. That is, the class does not use synchronized
methods.
• Further, this class was not created by you, but by a third
party, and you do not have access to the source code.
Thus, you can’t add synchronized to the appropriate
methods within the class.
simply put calls to the methods defined by this
class inside a synchronized block.
synchronized(object) {
// statements to be synchronized
}
public class Example
{
public static void main(String[] args) {
Table t=new Table();
Thread1 t1=new Thread1(t);
Thread2 t2=new Thread2(t);
t1.start();
t2.start();
}
}
Synchronized block