minte9
LearnRemember



Extending

Create a thread by extending Thread class.
 
/**
 * 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.
 * 
 * Threads can be created by using two mechanisms, extending Thread class ...
 * or implementing Runnable.
 */

package com.minte9.threads.create_thread;

public class Extending extends Thread { // Look Here
    public static void main(String[] args) {
  
        Thread t1 = new Extending();
        Thread t2 = new Extending();
        Thread t3 = new Extending();
        t1.start();
        t2.start();
        t3.start();

        /* 
            Thread-2 
            Thread-1
            Thread-0
            Thread-2
            Thread-0
            Thread-1
        */
    }

    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) {}
    }
}

Implementing

Best practice is to implement Runnable.
 
/**
 * Thread implementing Runnable.
 * Using lambdas the code is more concise and easy to read.
 */

package com.minte9.threads.create_thread;

public class Implementing {    
    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(() -> { // Lambdas
            System.out.println(
                Thread.currentThread().getName()
            );
        }).start(); // Thread-2

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

        /* 
            main
            Thread-0
            Thread-1
            Back in Main
            Thread-2
        */
    }
}

class MyClass implements Runnable {

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



  Last update: 381 days ago