Created
May 7, 2016 14:45
-
-
Save f3yisayo/09e4a52d59149a1f065fcc8e96b4b89f to your computer and use it in GitHub Desktop.
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
import java.util.concurrent.ExecutorService; | |
import java.util.concurrent.Executors; | |
public class App { | |
// Integer wrapper object to be passed by reference. | |
Integer sum = 0; | |
public static void main(String[] g){ | |
System.out.println("The total sum is " + new App().sum); | |
} | |
private App() { | |
// Creating a thousand threads is easier with a ThreadPool | |
ExecutorService executor = Executors.newFixedThreadPool(1000); | |
// You need only one instance of the AddSums class. | |
// Synchronization will only work on a per instance basis. | |
final AddSums addSums = new AddSums(); | |
for (int i = 0; i < 1000; i++) { | |
// Add the tasks to be performed. | |
executor.submit(addSums); | |
//System.out.println("Thread " + i +"'s sum: " + sum); | |
} | |
executor.shutdown(); | |
} | |
class AddSums implements Runnable{ | |
@Override | |
public synchronized void run() { | |
sum++; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment