继承Thread类

1.线程有默认名称:

package com.roocon.thread.t2;

public class Demo1 extends Thread {

    @Override
    public void run() {
            System.out.println(getName()+"线程执行了");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    }

    public static void main(String[] args) {
        Demo1 d1 = new Demo1();
        Demo1 d2 = new Demo1();
        d1.start();
        d2.start();
    }
}

输出结果:

Thread-1线程执行了
Thread-0线程执行了

 

2.自定义线程名称

package com.roocon.thread.t2;

public class Demo1 extends Thread {

    public Demo1(String name){
        super(name);
    }

    @Override
    public void run() {
            System.out.println(getName()+"线程执行了");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    }

    public static void main(String[] args) {
        Demo1 d1 = new Demo1("first-thread");
        Demo1 d2 = new Demo1("second-thread");
        d1.start();
        d2.start();
    }
}

输出结果:

second-thread线程执行了
first-thread线程执行了

 

posted @ 2017-12-06 23:16  凌晨六点半  阅读(625)  评论(0编辑  收藏  举报