Multithreading
volatile
helps facilitate atomic operation
sample code to trigger multiple threads
class Runner extends Thread {
public void run() {
for(int i=0; i<10; i++) {
System.out.println("Hello" + i);
}
}
}
public class App {
public static void main(String[] args) {
Runner runner1 = new Runner();
runner1.start();
Runner runner2 = new Runner();
runner2.start();
}
}
synchronized
keyword to use intrinsic lock to wait till one thread completes.
// Second thread have to wait until the first thread completes the
// execution due to instrinsic lock
public synchronized void increment() {
count++;
}
Intrinsic locks
Intrinsic locks play a role in both aspects of synchronization: enforcing exclusive access to an object's state and establishing happens-before relationships that are essential to visibility.
Every object has an intrinsic lock associated with it.
Project exercise repo - https://github.com/j143/java-threading-example
Top comments (0)