Java教程

JAVA创建线程的三种方法

本文主要是介绍JAVA创建线程的三种方法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

方法1:继承Thread类,并重写run方法

public class DemoTest {

    private static final Logger LOGGER = LoggerFactory.getLogger(DemoTest.class);

    public static class ThreadTest extends Thread {
        @Override
        public void run() {
            LOGGER.info("child thread");
        }
    }

    public static void main(String[] args) {
        LOGGER.info("Demo test");
        Thread thread = new ThreadTest();
        thread.start();
    }
}

方法2:实现Runnable接口,并实现run方法

public class DemoTest {

    private static final Logger LOGGER = LoggerFactory.getLogger(DemoTest.class);

    public static class RunableTest implements Runnable {
        @Override
        public void run() {
            LOGGER.info("child thread");
        }
    }
    public static void main(String[] args) {
        LOGGER.info("Demo test");
        Thread thread = new Thread(new RunableTest());
        thread.start();
    }
}

方法3:实现Callable<T>接口,并实现call方法

public class DemoTest {

    private static final Logger LOGGER = LoggerFactory.getLogger(DemoTest.class);

    public static class CallerTask implements Callable<String> {
        @Override
        public String call() throws Exception {
            LOGGER.info("child thread");
            return "return value";
        }
    }
    public static void main(String[] args) {
        LOGGER.info("Demo test");
        FutureTask<String> futureTask = new FutureTask<>(new CallerTask());
        Thread thread = new Thread(futureTask);
        thread.start();
        try {
            String result = futureTask.get();
            LOGGER.info("result: {}", result);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

第三种方法支持子线程返回任务执行的返回值,比前两种更灵活

这篇关于JAVA创建线程的三种方法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!