今天就跟大家聊聊有關(guān)java中怎樣創(chuàng)建線程,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
在山西等地區(qū),都構(gòu)建了全面的區(qū)域性戰(zhàn)略布局,加強(qiáng)發(fā)展的系統(tǒng)性、市場前瞻性、產(chǎn)品創(chuàng)新能力,以專注、極致的服務(wù)理念,為客戶提供做網(wǎng)站、成都網(wǎng)站設(shè)計(jì) 網(wǎng)站設(shè)計(jì)制作定制網(wǎng)站建設(shè),公司網(wǎng)站建設(shè),企業(yè)網(wǎng)站建設(shè),品牌網(wǎng)站建設(shè),成都全網(wǎng)營銷,成都外貿(mào)網(wǎng)站建設(shè)公司,山西網(wǎng)站建設(shè)費(fèi)用合理。
1. 繼承Thread類 2. 實(shí)現(xiàn)Runnable接口 3. 實(shí)現(xiàn)Callable接口,使用FutureTask方式 4. 使用線程池
package com.pimee.thread; /** * 繼承Thread創(chuàng)建線程 * @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; /** * 實(shí)現(xiàn)runnable接口創(chuàng)建線程 * @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(); } }
以上兩種方式實(shí)現(xiàn)都比較簡單,缺點(diǎn)很明顯,就是線程執(zhí)行后沒有返回值。且看下面帶有返回值的實(shí)現(xiàn)方式:
package com.pimee.thread; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; import java.util.concurrent.TimeoutException; /** * 實(shí)現(xiàn)callable接口,基于FutureTask方式實(shí)現(xiàn) * @author Bruce Shaw * */ public class CallableTest implements Callable{ public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException { CallableTest mc = new CallableTest(); FutureTask 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.*; /** * 基於線程池創(chuàng)建 * * @author Bruce Shaw * */ public class ThreadPoolTest implements Callable{ public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException { ExecutorService newCachedThreadPool = Executors.newSingleThreadExecutor(); Future 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..."; } }
看完上述內(nèi)容,你們對(duì)java中怎樣創(chuàng)建線程有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝大家的支持。