JVAVA并发编程(1):创建线程的三种方法

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

    }
}

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

posted @ 2021-12-20 19:54  取名好烦呀  阅读(46)  评论(0编辑  收藏  举报