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 – Android:问题图像分辨率


下一篇:Python--return后进行回调方法