Java使用Thread類代表線程,所有的線程對象都必須是Thread類或其子類的實例。Java可以用三種方式來創建線程,如下所示:
繼承Thread類創建線程
實現Runnable接口創建線程
使用Callable和Future創建線程
繼承Thread類創建線程
如下所示,繼承Thread類,重寫父類的run方法
public class TestThread extends Thread{
public static void main(String[] args) {
Thread thread = new TestThread();
thread.start();
}
@Override
public void run() {
super.run();
System.out.println("current thread is "+Thread.currentThread());
}
}
實現Runnable接口創建線程
實現Runnable接口創建線程,這種方式和上一種方式創建線程的區別是這種方式可以有返回值
public class RunableTest implements Runnable{
@Override
public void run() {
System.out.println("current thread is "+Thread.currentThread());
}
public static void main(String[] args) {
RunableTest runableTest = new RunableTest();
Thread thread = new Thread(runableTest);
thread.start();
}
}
使用Callable和Future創建線程
如下所示,實現Callable接口的call方法,通過Future對象的get方法,可以拿到call方法的返回值
public class CallableTest implements Callable<Integer>{
private int i;
private int j;
public CallableTest(int i, int j){
this.i = i;
this.j = j;
}
@Override
public Integer call() throws Exception {
int num = i+j;
Thread.sleep(3000);//模擬耗時操作
return num;
}
public static void main(String[] args) {
CallableTest callableTest = new CallableTest(5, 7);
FutureTask<Integer> task = new FutureTask<>(callableTest);
Thread thread = new Thread(task);
thread.start();
try {
Integer result = task.get();
System.out.println("Callable call方法返回的結果:"+result);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
將線程放入線程池中執行
如果希望在線程池中執行線程,可以使用ExecutorService類中的submit,invokeAll或者invokeAny方法。
public class CallableTest implements Callable<Integer>{
private int i;
private int j;
public CallableTest(int i, int j){
this.i = i;
this.j = j;
}
@Override
public Integer call() throws Exception {
int num = i+j;
Thread.sleep(3000);//模擬耗時操作
return num;
}
public static void main(String[] args) {
CallableTest callableTest = new CallableTest(5, 7);
ExecutorService executorService = Executors.newSingleThreadExecutor();
FutureTask<Integer> task = (FutureTask<Integer>) executorService.submit(callableTest);
try {
Integer result = task.get();
System.out.println("Callable call方法返回的結果:"+result);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
executorService.shutdown();
}
}