Created
February 3, 2023 00:42
-
-
Save madan712/9f0b4b5d66eb2cddfd3141b6b478e7a9 to your computer and use it in GitHub Desktop.
Java thread synchronization
This file contains hidden or 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
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