Thread in Java

Thread

Threads allows a program to operate more efficiently by doing multiple things at the same time. Threads can be used to perform complicated tasks in the background without interrupting the main program.

package anote;

public class Main {
    public static void main(String[] args) {
        System.out.println("main thread");
        Thread anotherThread = new AnotherThread(); 
        anotherThread.start();

        System.out.println("Hello again from the main thread.");
    }  
}

class AnotherThread extends Thread {

    @Override
    public void run(){
        System.out.println("Another thread.");
    }
}
main thread
Hello again from the main thread.
Another thread.

Runnable

You should not run the run method directly.

package anote;

public class Main {
    public static void main(String[] args) {
        System.out.println("main thread");
        Thread anotherThread = new AnotherThread(); 
        anotherThread.setName("another thread");
        anotherThread.start();

        System.out.println("Hello again from the main thread.");
        System.out.println("-----");

        Thread myRunnableThread = new Thread(new MyRunnable(){
            @Override
            public void run() {
                System.out.println("Hello from the anonymous class's implementation of run");
            }
        });
        myRunnableThread.start();
    }  
}

class AnotherThread extends Thread {

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

        try{
            Thread.sleep(1000);
        }catch(InterruptedException e){
            System.out.println("Another thread woke up");
        }
        System.out.println("After a second have passed");
    }
}

class MyRunnable implements Runnable{

    @Override
    public void run() {
        System.out.println("This is implementation of runnable");
    }
}
main thread
Hello again from the main thread.
-----
another thread
Hello from the anonymous class's implementation of run
After a second have passed

Leave a Reply

Your email address will not be published.

ANOTE.DEV