执行线程任务的写法有哪几种?

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**继承Thread*/
public class ThreadDemo extends Thread{
    public static void main(String[] args) {
        ThreadDemo threadDemo = new ThreadDemo();
        /**ThreadDemo继承了Thread类,可以调用Thread类的start()*/
        threadDemo.start();
        /**等同于 new ThreadDemo().start();*/
    }
    public void run() {
        System.out.println("马冬梅");
    }
}

/**实现Runnable类*/
public class ThreadDemo implements Runnable{
    public static void main(String[] args) {
        /**底层还是要调用Thread类*/
        new Thread(new ThreadDemo()).start();
    }
    /**重写run()方法*/
    @Override
    public void run() {
        System.out.println("马冬梅");
    }
}

/**匿名内部类*/
public class ThreadDemo {
    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("马冬梅");
            }
        }).start();
    }
}

/**Callable方法*/
public class ThreadDemo implements Callable {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask stringFutureTask = new FutureTask<>(new ThreadDemo());
        Thread thread = new Thread(stringFutureTask);
        thread.start();
        /**输出 马冬梅 */
        String result = stringFutureTask.get();
        System.out.println(result);
        /**输出 Thread-0 */
        /*String name = thread.getName();*/
        /*System.out.println(name);*/
    }

    @Override
    public String call() throws Exception {
        return "马冬梅";
    }
}

你可能感兴趣的:(JAVA后端开发,java,开发语言)