三种创建线程的方式

1.继承Thread

继承thread。

示例:

public class MyThread extends Thread {

    @Override
    public void run(){
        System.out.println("继承线程启动");
    }
    
    public static void main(String[] args){
        MyThread thread = new MyThread();
        thread.start();
    }
}

2.实现runable接口

示例:

public class RunableImpl implements Runnable{
    @Override
    public void run() {
        System.out.println("runnable线程启动");
    }

    public static void main(String[] arg){
        Thread myThread = new Thread(new RunableImpl());
        myThread.start();
    }
}

3.通过callable创建

示例:

public class CallableImpl implements Callable<Call>{
    @Override
    public Call call() throws Exception {
        Call callTest = new Call();
        callTest.setThreadName("MY CALLABLE");
        return callTest;
    }

    public static void main(String[] arg) throws Exception {
        CallableImpl callable = new CallableImpl();
        Call call = callable.call();
        System.out.println(call.getThreadName());
    }
}

三者区别:

thread与runable

一个通过继承实现,一个通过实现接口,由于Java是单继承,所以一旦继承了thread类就无法继承其他类,但是通过接口的方式,能实现其他多个接口或者继承其他类,所以runable可拓展性和灵活性要比thread好。

callable

能否抛出异常和返回值

发布了23 篇原创文章 · 获赞 19 · 访问量 1414

猜你喜欢

转载自blog.csdn.net/u012335601/article/details/89763303
今日推荐