Skip to content

Instantly share code, notes, and snippets.

@madan712
Created February 3, 2023 00:42
Show Gist options
  • Save madan712/9f0b4b5d66eb2cddfd3141b6b478e7a9 to your computer and use it in GitHub Desktop.
Save madan712/9f0b4b5d66eb2cddfd3141b6b478e7a9 to your computer and use it in GitHub Desktop.
Java thread synchronization
class ZapOne {
synchronized void print(int n) {
for (int i = 1; i <= 5; i++) {
System.out.println(n * i);
}
}
}
//Synchronized Function
class coding extends Thread {
ZapOne z;
coding(ZapOne z) {
this.z = z;
}
// First Thread
public void run() {
z.print(2);
}
}
class zap extends Thread {
ZapOne z;
zap(ZapOne z) {
this.z = z;
}
// Second Thread
public void run() {
z.print(10);
}
}
public class Main {
public static void main(String[] args) {
ZapOne obj = new ZapOne(); // Synchronised Object
coding z1 = new coding(obj);
zap z2 = new zap(obj); // Thread Object
z1.start();
z2.start(); // Start Function
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment