Java Concurrency Multithreading

Thread Thread Subclass Here is an example of creating a Java Thread subclass: public class MyThread extends Thread { public void run(){ System.out.println("MyThread running"); } } To create and start the above thread you can do like this: MyThread myThread = new MyThread(); myTread.start(); You can also create an anonymous subclass of Thread like this: Thread thread = new Thread(){ public void run(){ System.out.println("Thread Running"); } } thread.start(); Runnable Interface Implementation Java Class Implements Runnable public class MyRunnable implements Runnable { public void run(){ System.out.println("MyRunnable running"); } } Anonymous Implementation of Runnable Runnable myRunnable = new Runnable(){ public void run(){ System.out.println("Runnable running"); } } Java Lambda Implementation of Runnable Runnable runnable = () -> { System.out.println("Lambda Runnable running"); }; Starting a Thread With a Runnable Runnable runnable = new MyRunnable(); // or an anonymous class, or lambda... Thread thread = new Thread(runnable); thread.start(); The Java Memory Model Here is a diagram illustrating the call stack and local variables stored on the thread stacks, and objects stored on the heap: ...

2024-07-23 · 6 min · Ramesh