应用Thread类定义两个线程对象,要求每个线程输出它的名字,每隔300毫秒输出一次,共输出20次。
时间: 2024-03-06 12:47:03 浏览: 25
好的,以下是Java多线程的代码实现:
```java
class MyThread extends Thread{
public void run(){
for(int i=1;i<=20;i++){
System.out.println(getName());
try{
sleep(300);
}catch(InterruptedException e){
System.out.println(e);
}
}
}
}
public class Main{
public static void main(String[] args){
MyThread t1=new MyThread();
MyThread t2=new MyThread();
t1.start();
t2.start();
}
}
```
上述代码中,我们自定义了一个 MyThread 类,继承自 Thread 类,并重写了 run 方法。在 run 方法中,我们通过 getName 方法获取线程的名字,并使用 sleep 方法让线程每隔 300 毫秒输出一次,总共输出 20 次。
在 Main 类中,我们创建了两个 MyThread 对象 t1 和 t2,并通过 start 方法启动线程。此时,两个线程会同时执行 run 方法中的代码,输出各自的名字。