线程的四种创建方法

一、继承Thread类

创建一个类并继承Thread类,重写run方法。

创建该类的实例,调用start方法。

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

class MyThread extends Thread {
    @Override
    public void run() {
        //要执行的代码
    }
}

二、实现Runnable接口

创建一个任务类并实现Runnable接口,重写run方法。

创建该任务类的实例。

使用Thread类的有参构造传入任务类的实例。

调用Thread类的start方法。

public class test {
    public static void main(String[] args) {
        MyTask task = new MyTask();
        Thread thread = new Thread(task);
        thread.start();
    }
}

class MyTask implements Runnable{
    @Override
    public void run() {
        
    }
}

三、实现Callable接口

由于重写run方法无法抛出异常和返回值,如果想要抛出异常或想要返回值,可以实现Callable接口。

创建任务类实现Callable接口,重写call方法,创建任务类实例。

创建FutureTask实例,创建Thread类实例。调用start方法。

public class test {
    public static void main(String[] args) {
        MyTask task = new MyTask();
        FutureTask futureTask = new FutureTask(task);
        Thread thread = new Thread(futureTask);
        thread.start();
        //取得返回值
        try {
            futureTask.get();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
    }
}

class MyTask implements Callable {
    @Override
    public Object call() throws Exception {
        //要执行的代码
        return null;
    }
}

实现Callable可用泛型,如果要取得call方法的返回值,可以调用FutureTask实例的get方法,需要处理异常或抛出异常。

四、使用线程池

使用线程池的好处是:

当需要线程时,不用创建新线程,提高了响应速度。用完线程后不销毁,下次还可以使用,提高了资源重用率。方便对批量线程管理。

也可自己重写自己需要的线程池。

public class test {
    public static void main(String[] args) {
        //newFixedThreadPool(int) 创建有指定数目线程的线程池
        //newCachedThreadPool()  创建一个线程池,需要线程的时候,池中有可用线程就用,没有就新建
        ExecutorService  execute = Executors.newFixedThreadPool(10);
        //执行任务
        //execute.execute(一个实现Runnable接口的类);
        //执行任务
        //execute.submit(一个实现Runnable或Callable接口的类);
        //关闭执行器,不再接受任务,允许剩余任务运行结束
        //execute.shutdown();
        //立刻关闭执行器,返回剩余任务列表List<Runnable>
        //execute.showdownNow();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值