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();
}
}