如何在 Java 9 中的 JShell 中创建线程?

javaobject oriented programmingprogramming更新于 2025/9/11 23:08:17

JShell  是 Java 9 中引入的交互式 Java shell 工具,允许我们执行代码片段,并立即显示结果,而无需像 Java 那样声明 ma​​in() 方法。它是一个 REPL (读取-评估-打印-循环)工具,从 命令行 提示符运行。我们可以使用 JShell 创建 变量、方法、类、临时变量、外部库 等

在下面的代码片段中,我们可以通过扩展 Thread 类来创建线程。

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

在下面的代码片段中,控制台向用户打印"run() 方法中的线程"作为输出。

jshell> new ThreadTest().run();
Thread in run() method

相关文章


有用资源