如何在Java 9的JShell中创建线程?
JShell 是Java9中引入的交互式JavaShell工具,它使我们能够执行代码段,并立即显示结果,而无需像Java那样声明main()方法。它是一个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