How to create a thread in JShell in Java 9?

JavaObject Oriented ProgrammingProgramming

JShell is an interactive java shell tool introduced in Java 9 and allows us to execute code snippets, and shows the result immediately without declaring the main() method like Java. It is a REPL (Read-Evaluate-Print- Loop) tool and runs from the command-line prompt. We can create variables, methods, classes, scratch variables, external libraries, and etc using JShell

In the below code snippet, we can create a thread by extending the Thread class.

C:\Users\User>jshell
| Welcome to JShell -- Version 9.0.4
| For an introduction type: /help intro

jshell> class ThreadTest extends Thread {
...>       public void run() {
...>          System.out.println("Thread in run() method");
...>       }
...>       public static void main(String args[]) {
...>          ThreadTest t = new ThreadTest();
...>          t.start();
...>       }
...>    }
| created class ThreadTest


In the below code snippet, the console prints "Thread in run() method" as an output to the user.

jshell> new ThreadTest().run();
Thread in run() method
raja
Published on 27-Mar-2020 06:50:00
Advertisements