java线程的创建方式

  • 继承Thread类

//通过继承Thread类创建NewThread线程
class NewThread extends Thread{
    public void run(){
        System.out.println("create a thread by extends Thread");
    }
}
public class Main{
    public static void main(String[] args) {
//实例化一个NewThread线程对象
        NewThread newThread = new NewThread();
//调用start方法启动NewThread线程
        newThread.start();
    }
}

调用start()方法启动线程。
start()方法是要给native方法,通过在操作系统上启动一个新线程,并最终执行run方法来启动一个线程。run()方法内的代码是线程类的具体实现逻辑。

  • 实现Runnable接口
//通过实现Runnable接口创建线程
class NewThread implements Runnable{

    public void run() {
        System.out.println("create a thread by implements  Runnable");
    }
}
public class Main{
    public static void main(String[] args) {
//        实例化一个NewThread对象
        NewThread newThread = new NewThread();
//        创建一个线程对象,并传入已经实例化好的NewThread实例
        Thread thread = new Thread(newThread);
//        调用start方法启动一个线程
        thread.start();
    }
}

如果子类已经继承了一个类,就无法再直接继承Thread类,此时可以通过实现runnable接口创建线程。
过程:通过实现runnable接口创建线程,实例化线程对象newThread ,创建Thread类实例thread 并传入已经实例化好的newThread实例,调用线程的start方法启动线程。

  • 通过ExecutorService和Callable实现有返回值的线程
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

//通过实现callable接口创建NewThread线程
class NewThread implements Callable<String> {
    private String name;
    public NewThread(String name){
        //通过构造函数为线程传递参数,以定义线程名称
        this.name = name;
    }
    @Override
    public String call() throws Exception {
//        线程实现逻辑
        return name;
    }
}
public class Main{
    public static void main(String[] args) throws ExecutionException, InterruptedException {
//        创建固定大小为5的线程池
        ExecutorService pool = Executors.newFixedThreadPool(5);
//        创建多个有返回值的任务列表list
        List<Future> list = new ArrayList<Future>();
        for(int i = 0;i < 5;i++){
//            创建有返回值的线程实例
            Callable c = new NewThread(i + "");
//            提交线程,获取Future对象并保存到Future List中
            Future future = pool.submit(c);
            System.out.println("submit a callable thread:" + i);
            list.add(future);
        }
//        关闭线程池,等待线程执行结束
        pool.shutdown();
//        遍历所有线程的运行结果
        for (Future future:list){
//            从future对象上获取任务的返回值
            System.out.println("get the result from callable thread:"+ future.get().toString());
        }
    }
}

在主线程中开启多个线程并发执行一个任务,然后收集各个线程执行返回的结果并将最终结果汇总起来,需要用到Callable接口。

  • 基于线程池
    在每次需要时创建线程,运行结束后销毁时非常浪费资源的。可以使用线程池来创建线程。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main{
    public static void main(String[] args){
//        创建固定大小为10的线程池
        ExecutorService pool = Executors.newFixedThreadPool(10);
        for(int i = 0;i < 10;i++){
            pool.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() +" "+ "is running");
                }
            });
        }
    }
}

参考资料
《offer来了(原理篇)》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值