Three ways to create a thread way

1. inherited Thread

Inheritance thread.

Example:

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. Implement runable Interface

Example:

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. Create callable by

Example:

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());
    }
}

 

Between the three types:

thread与runable

Achieved through an inheritance, a by implementing the interface, since Java is a single inheritance, so once inherited the thread class can not inherit from other classes, but by way of the interface, multiple interfaces can inherit from other classes or other, so runable scalability thread and flexibility than good.

callable

You can throw exceptions and returns

Published 23 original articles · won praise 19 · views 1414

Guess you like

Origin blog.csdn.net/u012335601/article/details/89763303