创建线程的方式

1、继承Thread类

在项目中不建议使用这种方式创建线程,太消耗系统资源

public class Test1 {
    public static void main(String[] args) {
        new MyThread().start();
    }
}

class MyThread extends Thread {
    @Override
    public void run() {
        // do some thing……
    }
}

2、实现Runnable接口

该方式实现的线程不带返回值,不抛异常

public class Test2 {

    public static void main(String[] args) {
        // 参数根据实现需要改变,分别是 核心数量、最大数量、空闲时间、时间单位、工作队列
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1,
                60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(1));

        // 用线程池运行
        threadPoolExecutor.execute(new A());

        // 关闭线程池(在web项目中不需要关闭)
        threadPoolExecutor.shutdown();
    }
}

class A implements Runnable {

    @Override
    public void run() {
        // do some thing……
    }
}

3、实现Callable接口

该方式实现的线程带返回值,可以抛出异常

public class Test3 {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 参数根据实现需要改变,分别是 核心数量、最大数量、空闲时间、时间单位、工作队列
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1,
                60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(1));

        // 用线程池运行
        Future<Object> future = threadPoolExecutor.submit(new B());

        // 获取执行完之后的返回值,这里会阻塞,直至线程运行完毕
        Object object = future.get();

        // 关闭线程池(在web项目中不需要关闭)
        threadPoolExecutor.shutdown();
    }
}

class B implements Callable<Object> {

    // 返回类型根据实际需要定义
    @Override
    public Object call() throws Exception {
        // do some thing……
        return null;
    }
}

你可能感兴趣的:(Java,java,线程,多线程)