Skip to content

Instantly share code, notes, and snippets.

@xuhang57
Last active March 27, 2019 18:36
Show Gist options
  • Save xuhang57/1d629391466771f1943c766b2cb40c91 to your computer and use it in GitHub Desktop.
Save xuhang57/1d629391466771f1943c766b2cb40c91 to your computer and use it in GitHub Desktop.
Code Snippet on Java Concurrency
/*
Using the synchronized keyword to protect blocks of code within a method.
This block is guarded by a key, which can be either a string or an object
This key is called the lock
*/
public synchronized void critial() {
// some thread critical stuff
}
public class MyRunnable implements Runnable {
private final long count;
MyRunnable(long count) {
this.count = count;
}
@Override
public void run() {
long sum = 0;
for (long i = 1; i < count; i++) {
sum += 1;
}
System.out.println(sum);
}
}
public class MyCallable implements Callable<Long> {
@Override
public Long call() throws Exception {
long sum = 0;
for (long i = 0; i <= 100; i++) {
sum += i;
}
return sum;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment