PROGRAMMING

m9/ JAVA
REMEMBERS




Last update:   05-10-2021

CREATE THREADS

p6 Threads are not separate processes on the OS (user feels is like separate processes). A Java application starts up a main thread, main() on the bottom of the stack. A new thread creats a separate call stack, run() at the botttom of the stack. p18 Threads can be created by using two mechanisms.
 
class App extends Thread { // Look Here

    public static void main(String[] args) {
  
        Thread t1 = new App();
        Thread t2 = new App();
        Thread t3 = new App();
        t1.start();
        t2.start();
        t3.start();
    }

    public void run() {
        try {
            String name = Thread.currentThread().getName();

            System.out.println(name);
            Thread.sleep(1000);

            System.out.println(name);
            Thread.sleep(1000);

        } catch (InterruptedException ex) {}
    }
}

/* 
    Thread-2 
    Thread-1
    Thread-0
    Thread-2
    Thread-0
    Thread-1
*/
... 21 lines
 
Best practice is to implement Runnable.
 
class App {
    
    public static void main(String[] args) throws InterruptedException {

        System.out.println(
            Thread.currentThread().getName()
        ); // main


        new Thread(
            new MyClass()
        ).start(); // Tread-0


        new Thread(new Runnable() {
            public void run() {
                System.out.println(
                    Thread.currentThread().getName()
                );
            }
        }).start(); // Thread-1


        new Thread(() -> {
            System.out.println(
                Thread.currentThread().getName()
            );
        }).start(); // Thread-2


        System.out.println("Back in Main");
    }
}

class MyClass implements Runnable {

    @Override public void run() {
        System.out.println(
            Thread.currentThread().getName()
        );
    }
}

/* 
    main
    Thread-0
    Thread-1
    Back in Main
    Thread-2
*/
... 31 lines
 

Questions    
Thread Sleep

        A B C D E F
🔔
1/3