Skip to content

Instantly share code, notes, and snippets.

@damithadayananda
Last active December 29, 2018 06:43
Show Gist options
  • Save damithadayananda/b05bc4a664e1c4b5f7fd18e6f619c0eb to your computer and use it in GitHub Desktop.
Save damithadayananda/b05bc4a664e1c4b5f7fd18e6f619c0eb to your computer and use it in GitHub Desktop.
show the usage of synchronized block in java
public class main {
public static void main(String[] args){
new mainSynchronize();
}
}
package synchronize;
public class mainSynchronize {
final MathClass mathClass = new MathClass();
public mainSynchronize(){
Runnable r = new Runnable() {
@Override
public void run() {
try{
mathClass.printNumbers(3);
}catch (InterruptedException e){
e.printStackTrace();
}
}
};
new Thread(r,"ONE").start();
new Thread(r,"TWO").start();
}
}
package synchronize;
public class MathClass {
synchronized void printNumbers(int n) throws InterruptedException
{
for (int i=1; i<=n;i++){
System.out.println(Thread.currentThread().getName() + "::" + i);
Thread.sleep(500);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment