用java编写。请编写一个类,类名为MulThread ,该类实现Runnable接口。类中定义了含一个字符串参数的构造函数,设置线程名称;其中的run( )方法如下实现:方法中先在命令行显示“begin”+线程名,然后休眠1秒的时间,最后显示线程结束信息: "finished"+线程名。编写Application,在其中通过Runnable创建MulThread类的三个线程对象t1、t2、t3,并启动这三个线程。
时间: 2023-06-27 18:05:07 浏览: 103
MulThread类的代码如下:
```java
public class MulThread implements Runnable {
private String threadName;
public MulThread(String threadName) {
this.threadName = threadName;
}
@Override
public void run() {
System.out.println("begin " + threadName);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("finished " + threadName);
}
}
```
Application类的代码如下:
```java
public class Application {
public static void main(String[] args) {
MulThread t1 = new MulThread("Thread 1");
MulThread t2 = new MulThread("Thread 2");
MulThread t3 = new MulThread("Thread 3");
Thread thread1 = new Thread(t1);
Thread thread2 = new Thread(t2);
Thread thread3 = new Thread(t3);
thread1.start();
thread2.start();
thread3.start();
}
}
```
在main方法中,我们创建了三个MulThread对象t1、t2、t3,并分别将它们作为参数传入了三个Thread对象的构造函数中。最后,我们启动了这三个线程。运行该程序,会输出以下结果:
```
begin Thread 1
begin Thread 2
begin Thread 3
finished Thread 1
finished Thread 2
finished Thread 3
```