Java实现线程的几种方式

Posted by 小白 on December 13, 2016

继承Thread,覆盖run()方法

public class ThreadA extends Thread {
    @Override
    public void run(){
        super.run();
        try {
            Thread.sleep(5000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("这是线程A");
    }
}

启动线程:

 public static void main(String[] args){
        ThreadA threadA=new ThreadA();
        threadA.start();
        System.out.println("这是主线程");
 }

由于Java只能继承一个父类,所以,看着办。

实现Runnable接口,实现run()方法

public class ThreadB implements Runnable {
    @Override
    public void run() {
        try {
            Thread.sleep(5000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("这是线程B");
    }
}

启动线程:

    public static void main(String[] args){
        ThreadB threadB=new ThreadB();
        new Thread(threadB).start();//这里不同哦
        System.out.println("这是主线程");
    }

实现Callable接口,实现call()方法

public class ThreadC implements Callable<String> {
    @Override
    public String call() throws Exception {
        Thread.sleep(5000L);
        System.out.println("这是线程C");
        return "thread B";
    }
}

启动线程:

    public static void main(String[] args){
        ThreadC threadC=new ThreadC();
        FutureTask<String> futureTask=new FutureTask<String>(threadC);//这里又不一样了哦
        new Thread(futureTask).start();
        System.out.println("主线程开始...");
        //主线程运行时,才会走下面的代码
        try{
            System.out.println("得到的返回结果"+futureTask.get());
        }catch (InterruptedException e){
            e.printStackTrace();
        }catch (ExecutionException e){
            e.printStackTrace();
        }
        System.out.println("...主线程结束");
    }