多线程作业(2018.08.23)

4、设计一个线程操作类,要求可以产生三个线程对象,并可以分别设置三个线程的休眠时间,如下所示:

线程A,休眠10秒
线程B,休眠20秒
线程C,休眠30秒
要求:
采用以下两种方式方式分别实现该功能:
1,Tread类
2,Runnable
这是实现Runnable接口方法
class MyTh implements Runnable{
    private String name;
    private int time;
    public MyTh (String name,int time){
        this.name = name ;//设置线程名称
        this.time = time ;//设置休眠时间
    }
    public void run(){   //重写run方法
        try {
            Thread.sleep(this.time);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(this.name+",休眠时间为:"+this.time/1000+"秒");
    }
}
public class thread_02 {

    public static void main(String[] args) {
        MyTh a = new MyTh("线程1", 10000);  //定义休眠的对象,并设置休眠时间
        MyTh b = new MyTh("线程2", 20000);
        MyTh c = new MyTh("线程3", 30000);
        new Thread(a).start();  //启动线程
        new Thread(b).start();
        new Thread(c).start();
    }
}
 1 这是继承Thread类实现
 2 class MyThread extends Thread{
 3     private int time;
 4     public MyThread (String name,int time){
 5         super(name);
 6         this.time = time ;
 7     }
 8     public void run(){
 9         try {
10             Thread.sleep(this.time);
11         } catch (Exception e) {
12             e.printStackTrace();
13         }
14         System.out.println(Thread.currentThread().getName()+",休眠时间为:"+this.time/1000+"秒");
15     }
16 }
17 public class thread_01 {
18 
19     public static void main(String[] args) {
20         MyThread a = new MyThread("线程1", 10000);
21         MyThread b = new MyThread("线程2", 20000);
22         MyThread c = new MyThread("线程3", 30000);
23         a.start();
24         b.start();
25         c.start();
26     }
27 }

运行结果:

1 线程1,休眠时间为:10秒
2 线程2,休眠时间为:20秒
3 线程3,休眠时间为:30秒