java · 2019-06-29 0

Java创建线程三种方式

一、继承Thread类

继承Thread类,重写run()方法。调用对象start()方法,可启动线程,线程会执行run()方法。

//继承Thread,重写run()方法
class MyThread extends Thread{

    @Override
    public void run() {
        for(int i = 0; i < 10; i++){
            System.out.println(Thread.currentThread().getName() + ":" + i);
        }
    }
}

public class ThreadTest {
    public static void main(String[] args){
//        创建线程
        MyThread t1 = new MyThread();
//        启动线程
        t1.start();
    }
}

二、实现Runnable接口

//实现Runnable接口
class MyRunnable implements Runnable{

    @Override
    public void run() {
        for(int i = 0; i < 10; i++){
            System.out.println(i);
        }
    }

}

public class ThreadTest {
    public static void main(String[] args){
//        创建MyRunnable对象
        MyRunnable r = new MyRunnable();
//        创建线程
        Thread t = new Thread(r);
//        启动线程
        t.start();
    }
}

三、实现Callable接口

与Runnable接口不同的是,Callable接口的call()方法可以返回值。通过FutureTask可以获得线程执行后的返回值。

//实现Callable接口
class NumCallable implements Callable {
    //  重写call()方法
    @Override
    public Object call() throws Exception {
        int sum = 0;
        for (int i = 0; i < 10; i++) {
            System.out.println(i);
            sum += i;
        }
        return sum;
    }

}

public class ThreadTest {
    public static void main(String[] args) {
        NumCallable numCallable = new NumCallable();

//      FutureTask可获取Callable任务的执行结果
        FutureTask futureTask = new FutureTask(numCallable);

        Thread t = new Thread(futureTask);
        t.start();

        try {
//            get返回值即为FutureTask构造器参数Callable实现类重新的call()的返回值
            Object sum = futureTask.get();
            System.out.println(sum);
        } catch (ExecutionException | InterruptedException e) {
            e.printStackTrace();
        }

    }
}

四、创建线程池

class NumberThread implements Runnable{

    @Override
    public void run() {
        for(int i = 0; i < 10; i++){
            System.out.println(Thread.currentThread().getName() + " : " + i);
        }
    }
}

public class ThreadPool {

    public static void main(String[] args) {
//        提供指定线程数量的线程池
        ExecutorService service = Executors.newFixedThreadPool(10);
        NumberThread t = new NumberThread();
        service.execute(t);    //适合适用于Runnabe
        service.execute(t);    //适合适用于Runnabe
//      service.submit()                         //适合适用于Callable
        service.shutdown();
    }
}