怎么在visual Studio code里实现class KY8_1 extends Thread { public SimpleThread(String str) { super(str); } public void run() { for (int i = 0; i < 10; i++) { System.out.println(i + " " + getName()); try { sleep((int)(Math.random() * 1000)); } catch (InterruptedException e) {} } System.out.println("DONE! " + getName()); } } public class TwoThreadsTest { public static void main (String[] args) { new SimpleThread("Go to Beijing??").start(); new SimpleThread("Stay here!!").start(); } }
时间: 2024-02-14 20:17:08 浏览: 134
Java_abstract_example.rar_abstract class_抽象
在 Visual Studio Code 中实现这个类和测试程序的步骤如下:
1. 新建一个 Java 文件,例如 TwoThreadsTest.java,并在文件中输入以下代码:
```
class KY8_1 extends Thread {
public KY8_1(String str) {
super(str);
}
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(i + " " + getName());
try {
sleep((int)(Math.random() * 1000));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("DONE! " + getName());
}
}
public class TwoThreadsTest {
public static void main(String[] args) {
new KY8_1("Go to Beijing??").start();
new KY8_1("Stay here!!").start();
}
}
```
2. 保存文件并在 Visual Studio Code 中打开终端。
3. 进入文件所在的文件夹并使用以下命令进行编译:
```
javac TwoThreadsTest.java
```
4. 编译成功后,使用以下命令运行程序:
```
java TwoThreadsTest
```
5. 程序会输出两个线程的执行结果,如下所示:
```
0 Go to Beijing??
0 Stay here!!
1 Go to Beijing??
1 Stay here!!
2 Stay here!!
2 Go to Beijing??
3 Stay here!!
3 Go to Beijing??
4 Stay here!!
4 Go to Beijing??
5 Go to Beijing??
5 Stay here!!
6 Stay here!!
6 Go to Beijing??
7 Go to Beijing??
7 Stay here!!
8 Stay here!!
8 Go to Beijing??
9 Stay here!!
9 Go to Beijing??
DONE! Stay here!!
DONE! Go to Beijing??
```
这样就可以在 Visual Studio Code 中成功实现这个类和测试程序了。
阅读全文