Last active
December 29, 2018 06:43
-
-
Save damithadayananda/b05bc4a664e1c4b5f7fd18e6f619c0eb to your computer and use it in GitHub Desktop.
show the usage of synchronized block in java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class main { | |
public static void main(String[] args){ | |
new mainSynchronize(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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