DEV Community

Janardhan Pulivarthi
Janardhan Pulivarthi

Posted on • Updated on

Day 16 of 100 - Java: Multi-threading

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();
    }
}
Enter fullscreen mode Exit fullscreen mode

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++;
    }
Enter fullscreen mode Exit fullscreen mode

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

https://www.udemy.com/course/java-multithreading

Top comments (0)