今天就跟大家聊聊有關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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。