今天就跟大家聊聊有关java中怎样创建线程,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
1. 继承Thread类 2. 实现Runnable接口 3. 实现Callable接口,使用FutureTask方式 4. 使用线程池
package com.pimee.thread; /** * 继承Thread创建线程 * @author Bruce Shaw * */ public class ThreadTest extends Thread { public static void main(String[] args) { ThreadTest test = new ThreadTest(); test.start(); } @Override public void run() { System.out.println("This is TestThread..."); } }
package com.pimee.thread; /** * 实现runnable接口创建线程 * @author Bruce Shaw * */ public class RunnableTest implements Runnable { private static int test = 10; @Override public void run() { System.out.println("This is RunnableTest..."); } public static void main(String[] args) { RunnableTest test = new RunnableTest(); new Thread(test).start(); } }
以上两种方式实现都比较简单,缺点很明显,就是线程执行后没有返回值。且看下面带有返回值的实现方式:
package com.pimee.thread; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; import java.util.concurrent.TimeoutException; /** * 实现callable接口,基于FutureTask方式实现 * @author Bruce Shaw * */ public class CallableTest implements Callable<String> { public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException { CallableTest mc = new CallableTest(); FutureTask<String> ft = new FutureTask<>(mc); Thread thread = new Thread(ft); thread.start(); System.out.println(ft.get()); } @Override public String call() throws Exception { System.out.println("Callable is running..."); return "Callable finished and return value..."; } }
package com.pimee.thread; import java.util.concurrent.*; /** * 基於线程池创建 * * @author Bruce Shaw * */ public class ThreadPoolTest implements Callable<String> { public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException { ExecutorService newCachedThreadPool = Executors.newSingleThreadExecutor(); Future<String> future = newCachedThreadPool.submit(new CallableTest()); try { System.out.println(future.get()); } catch (Exception e) { e.printStackTrace(); } finally { newCachedThreadPool.shutdown(); } } @Override public String call() throws Exception { System.out.println("Callable is running..."); return "Callable finished and return value..."; } }
看完上述内容,你们对java中怎样创建线程有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。