public SubThread extends Thread {
@override
public void run() {
...
}
}使用时:Thread subThread = new SubThread(); subThread.start();可以使用Thread类已有的函数进行操作。
public SubThread implements Runnable {
public void run() {
// doSomething...
}
}使用时:SubThread subThread = new SubThread(); Thread thread = new Thread(subThread); thread.start();使用该方式实现的类其实是一个普通类,只是它实现了线程的run方法,因而将其注册到Thread类的对象中才能作为一个线程运行。
public SubThread implements Callable<String> {
public String call() {
// do something...
}
}可以看出,通过这种方式实现的线程带有返回值,Callable<String>指定返回值类型,并且Callable可以抛出异常,而Runnable则不能。public class TestCallable implements Callable<String> {
public String call() throws InterruptedException {
Thread.sleep(5000);
return "call return";
}
public static void main(String[] args) {
TestCallable test = new TestCallable();
FutureTask<String> futrue = new FutureTask<String>(test);
Thread thread = new Thread(futrue);
thread.start();
// 在需要结果之前,可以坐其他事
System.out.println("hello");
try {
System.out.println(futrue.get());
} catch (ExecutionException e) {
System.out.println("执行callable时出错");
} catch (InterruptedException e) {
System.out.println("执行callable时出错");
}
System.out.println("结束语");
}
}hello call return 结束语
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/linux2_scdn/article/details/48046901