JAVA建立執行緒的三種方法
阿新 • • 發佈:2021-12-20
方法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 staticvoid 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 { @Overridepublic 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(); } } }
第三種方法支援子執行緒返回任務執行的返回值,比前兩種更靈活