Skip to content

Instantly share code, notes, and snippets.

@finnkvan
Created October 24, 2018 18:55
Show Gist options
  • Select an option

  • Save finnkvan/dc95675fcaf216d34f2743665cbae878 to your computer and use it in GitHub Desktop.

Select an option

Save finnkvan/dc95675fcaf216d34f2743665cbae878 to your computer and use it in GitHub Desktop.
synchronized example
package com.pivincii;
public class AsynDemo {
private Object mutex = new Object();
public void countTo(int value) {
synchronized (mutex) {
int count = 0;
while (count < value) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
count++;
System.out.println(Thread.currentThread() + " counted " + count);
}
}
}
public static void main(String[] args) {
AsynDemo asynDemo = new AsynDemo();
new Thread(() -> asynDemo.countTo(3)).start();
new Thread(() -> asynDemo.countTo(3)).start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment