Skip to content

Instantly share code, notes, and snippets.

@sbcd90
Created June 27, 2016 03:18
Show Gist options
  • Save sbcd90/f21dbb7d7efb3fcbab921bf68b9351a7 to your computer and use it in GitHub Desktop.
Save sbcd90/f21dbb7d7efb3fcbab921bf68b9351a7 to your computer and use it in GitHub Desktop.
package com.sap.sync;
class SynchronizationTest {
public int i;
// synchronize locks a block of code printB or method like printA
// only one thread can access a synchronized block at a single point in time.
public synchronized void printA(int a) {
for (int count=0;count < 5;count++) {
System.out.println(a);
try {
Thread.sleep(400);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void printB(int b) {
// this has the same effect as printA
// either synchronize a block of code or the full method like printA
synchronized (this) {
for (int count = 0; count < 5; count++) {
System.out.println(b);
try {
Thread.sleep(400);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
public class SynchronizedTest {
public static void main(String[] args) {
SynchronizationTest syncTest = new SynchronizationTest();
Thread t1 = new Thread(){
@Override
public void run() {
syncTest.printA(2);
// syncTest.printB(2);
}
};
Thread t2 = new Thread(){
@Override
public void run() {
syncTest.printA(4);
// syncTest.printB(4);
}
};
t1.start();
t2.start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment