Last active
March 27, 2019 18:36
-
-
Save xuhang57/1d629391466771f1943c766b2cb40c91 to your computer and use it in GitHub Desktop.
Code Snippet on Java Concurrency
This file contains 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
/* | |
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