创建线程的三种方式

66 阅读1分钟

1.继承Thread类重写run方法(不带返回参数)

class MyThread extends Thread{
    @Override
    public void run() {
        System.out.println("继承Thread类重写run方法");
    }
}
@org.junit.Test
public void test01(){
    MyThread myThread = new MyThread();
    myThread.start();
}

2.实现runnable接口,重写run方法(不带返回参数)

@org.junit.Test
public void test02(){
    Runnable runnable = new Runnable() {
        public void run() {
            System.out.println("实现runnable接口,重写run方法");
        }
    };
    Thread thread = new Thread(runnable);
    thread.start();
}

3.实现callable接口,重写call方法(带返回参数)

@org.junit.Test
public void test03() throws ExecutionException, InterruptedException {
    Callable<Integer> callable = new Callable<Integer>() {
        public Integer call() throws Exception {
            System.out.println("实现callable接口,重写call方法");
            return 1;
        }
    };
    FutureTask<Integer> futureTask = new FutureTask<Integer>(callable);
    Thread thread = new Thread(futureTask);
    thread.start();
    //调用的future.get()方法,会阻塞当前线程,直到返回结果,大大降低性能
    Integer integer = futureTask.get();
    System.out.println("返回值:" + integer);
}