0
点赞
收藏
分享

微信扫一扫

Java多线程技术总结

westfallon 2022-02-01 阅读 76
java后端

1.获得多线程的方法有几种?

2.Runnable 对比 

import java.util.concurrent.Callable;

//创建类MyThread实现Runnable接口
public class MyThread implements Runnable {
    @Override
    public void run() {

    }
}

//创建类MyThread2实现Callable接口
class MyThread2 implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        return null;
    }
}

问题:callable 接口与 runnable 接口的区别?

答:(1)是否有返回值

(2)是否抛异常

(3)落地方法不一样,一个是 run ,一个是 call

程序代码

 

import java.util.concurrent.Callable;

//创建类MyThread实现Runnable接口
public class MyThread implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        Thread.sleep(4000);
        System.out.println(Thread.currentThread().getName() + "  ******come in call");
        return 200;
    }
}
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class CallableDemo {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        FutureTask<Integer> ft = new FutureTask<Integer>(new MyThread());
        new Thread(ft, "AA").start();
        System.out.println(Thread.currentThread().getName() + "----main");
        Integer result = ft.get();
        System.out.println("**********result: "+result);
    }
}
举报

相关推荐

0 条评论