设计一个线程操作类,可以产生3个线程对象,并分别设置3个线程的休眠时间:
- 线程A,休眠2秒
- 线程B,休眠5秒
- 线程C,休眠8秒
实现一 ------ 继承Thread类
class MyThread extends Thread{
private int time;
public MyThread(String name,int time){
super(name);
this.time = time;
}
public void run(){
try {
Thread.sleep(this.time);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "睡眠" + this.time/1000 + "秒");
}
}
public class ExampleThreadDemo01 {
public static void main(String[] args) {
MyThread mt1 = new MyThread("线程A",2000);
MyThread mt2 = new MyThread("线程B",5000);
MyThread mt3 = new MyThread("线程C",8000);
mt1.start();
mt2.start();
mt3.start();
}
}
程序运行结果:
实现二 ------ 实现 Runnable 接口
class MyThread implements Runnable{
private String name;
private int time;
public MyThread(String name,int time){
this.name = name;
this.time = time;
}
public void run(){
try {
Thread.sleep(this.time);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(this.name + "睡眠" + this.time/1000 + "秒");
}
}
public class ExampleRunnableDemo01 {
public static void main(String[] args) {
MyThread mt1 = new MyThread("线程A",2000);
MyThread mt2 = new MyThread("线程B",5000);
MyThread mt3 = new MyThread("线程C",8000);
new Thread(mt1).start();
new Thread(mt2).start();
new Thread(mt3).start();
}
}
程序运行结果: