Thread,Callable,Runnable

Thread使用:
class mythread1 extends Thread {
    int num=10;
    @Override
    public void run() {
        while(num>0) {
            System.out.println(Thread.currentThread()+"-"+num--);
        }
    }
}
new mythread1().start();

Runnable接口使用:

class mythread2 implements Runnable {
    private int num = 10;
    @Override
    public void run() {
        while(num>0) {
            System.out.println(Thread.currentThread().getName()+"-"+num--);
        }
    }
}
 mythread2 a = new mythread2();
 mythread2 b = new mythread2();
 new Thread(a).start();
 new Thread(b).start();

Callable接口使用:

class mythread3 implements Callable<Integer>{
    int num=10;
    @Override
    public Integer call() throws Exception {        
        while(num>0) {
            System.out.println(Thread.currentThread().getName()+"-"+num--);
        }
        return num; 
    }    
}
mythread3 my3=new mythread3();
FutureTask<Integer> ft = new FutureTask<>(my3); 
new Thread(ft,"有返回的线程").start();
try {
    System.out.println("子线程的返回值:"+ft.get());
} catch (InterruptedException e) {
    e.printStackTrace();
} catch (ExecutionException e) {
    e.printStackTrace();
} 
new Thread(ft,"有返回的线程").start();
Callable和Runnable的区别:
1、Callable中定义的是call()方法,Runnable中定义的是run()方法
2、Callable中的call()方法可以返回执行任务后的结果,Runnable中的run()方法无法获得返回值
3、Callable中的call()方法定义了throws Exception抛出异常,抛出的异常可以在主线程Future.get()时被主线程捕获;Runnable中的run()方法没有定义抛出异常,运行任务时发生异常时也会上抛,因为即使不加默认也会上抛RuntimeException,但异常无法被主线程获取
4、运行Callable任务可以拿到一个Future对象代表异步运算的结果

 

posted @ 2019-03-16 00:36  LeeJuly  阅读(140)  评论(0)    收藏  举报