线程的建立---3种方式

1.继承Thread类,重写Run方法

    class mythread extends Thread{
    private String title;
    public mythread(String title) {
        super();
        this.title = title;
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        super.run();
        for(int i=0;i<10;i++){
            System.out.println(this.title+".x :"+i);
        }
    }
}
jvm

2.实现Runnable接口,重写run方法

//这样实现多线好点,由于能够不受单继承的局限
class mythread implements Runnable{
    private String title;
    public mythread(String title) {
        super();
        this.title = title;
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        for(int i=0;i<10;i++){
            System.out.println(this.title+".x :"+i);
        }
    }
}
ide

    2.1,看源码进行分析一个问题;

//为啥不调用run而调用start
        // private native void start0();
        //它内部调用了本地的系统调用方法start0,从底层jvm进行对资源的
        //协调,start最后也是要call run();this

3.实现Callable接口,重写call方法

//runnable没返回值,callable有返回值
class Mythread implements Callable<String>{
    private String title;
    public Mythread(String title) {
        this.title=title;
    }
    @Override
    public String call() throws Exception {
        for(int x=0;x<10;x++){
            System.out.println(this.title+".x "+x);
        }
        return "ok";
    }
}
spa

public static void main(String[] args) throws Exception {
        FutureTask<String> task=new FutureTask<>(new Mythread("A"));
        new Thread(task).start();
        System.out.println(task.get());
    }
.net

4.Callable与Thread的关系

    4.1能够查看源代码知道

相关文章
相关标签/搜索