-
-
Save msiemens/f5f6ef97163087e51fd3 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.ArrayList; | |
class SyncedExample extends Thread { | |
private static int counter = 0; | |
private static final Object lock = new Object(); | |
public static void main(String[] args) throws Exception { | |
ArrayList<SyncedExample> threads = new ArrayList<SyncedExample>(); | |
// Create 10 threads | |
for (int i = 0; i < 10; i++) { | |
SyncedExample thread = new SyncedExample(); | |
thread.start(); | |
threads.add(thread); | |
} | |
// Wait for all threads to finish | |
for (SyncedExample thread : threads) { | |
thread.join(); | |
} | |
System.out.println(counter); | |
} | |
// The function that will be called in each thread | |
public void run() { | |
for (int i = 0; i < 100_000; i++) { | |
synchronized(lock){ | |
counter += 1; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment