目录
实现java.util.concurrent.Callable接口
目标
熟练使用基本方式创建并线程,并调用线程执行业务。
概念
创建线程的两种方法
- 继承java.lang.Thread类;
- 实现java.lang.Runnable接口;
- 备注:虽然实现java.util.concurrent.Callable接口也能创建线程,但是该方法与实现java.lang.Runnable接口创建线程类似,所以并为一类。面试和日常学习交流也可以说该接口的实现也是创建线程的第三种方法。
JDK对java.lang.Thread类的描述如下:
There are two ways to create a new thread of execution.
One is to declare a class to be a subclass of Thread. This subclass should override the run method of class Thread. An instance of the subclass can then be allocated and started.
The other way to create a thread is to declare a class that implements the Runnable interface. That class then implements the run method. An instance of the class can then be allocated, passed as an argument when creating Thread, and started.JDK对java.util.concurrent.Callable类的描述如下:
The Callable interface is similar to Runnable, in that both are designed for classes whose instances are potentially executed by another thread. A Runnable, however, does not return a result and cannot throw a checked exception.
实战
继承java.lang.Thread类
package com.ctx.concurrent.thread;
/**
* 创建线程
* 计算输入的两个数之和
*/
public class ThreadSumTest extends Thread{
long num1;
long num2;
ThreadSumTest(long num1, long num2) {
this.num1 = num1;
this.num2 = num2;
}
@Override
public void run() {
System.out.println(num1+num2);
}
}
package com.ctx.concurrent.thread;
public class ThreadTest {
public static void main(String[] args) {
//求和
ThreadSumTest t = new ThreadSumTest(100,200);
new Thread(t).start();
}
}
实现java.lang.Runnable接口
package com.ctx.concurrent.thread;
/**
* 创建线程
* 计算输入的两个数之和
*/
public class RunnableSumTest implements Runnable{
long num1;
long num2;
RunnableSumTest(long num1, long num2) {
this.num1 = num1;
this.num2 = num2;
}
@Override
public void run() {
System.out.println(num1+num2);
}
}
package com.ctx.concurrent.thread;
public class ThreadTest {
public static void main(String[] args) {
//求和
RunnableSumTest t2 = new RunnableSumTest(100,200);
new Thread(t2).start();
}
}
实现java.util.concurrent.Callable接口
package com.ctx.concurrent.thread;
import java.util.concurrent.Callable;
/**
* 创建线程
* 计算输入的两个数之和
*/
public class CallableSumTest implements Callable {
long num1;
long num2;
CallableSumTest(long num1, long num2) {
this.num1 = num1;
this.num2 = num2;
}
/**
* 有返回值,能抛出异常。
* @return
* @throws Exception
*/
@Override
public Long call() throws Exception {
long num3=num1+num2;
return num3;
}
}
import java.util.concurrent.FutureTask;
public class ThreadTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//求和
CallableSumTest t3 = new CallableSumTest(100,200);
FutureTask task = new FutureTask(t3);
Thread thread = new Thread(task);
thread.start();
System.out.println(task.get());
}
}