java创建线程的方式有几种?

java创建线程的方式有几种?这篇文章运用了实例代码展示,代码非常详细,可供感兴趣的小伙伴们参考借鉴,希望对大家有所帮助。

创新互联专注于企业成都全网营销、网站重做改版、福鼎网站定制设计、自适应品牌网站建设、H5场景定制商城网站建设、集团公司官网建设、成都外贸网站建设公司、高端网站制作、响应式网页设计等建站业务,价格优惠性价比高,为福鼎等各大城市提供网站开发制作服务。

1、继承Thread类

public class ThreadCreator extends Thread{

    public static void main(String[] args) {
       //第一种方式:
       ThreadCreator creator = new ThreadCreator();
       Thread thread = new Thread(creator,"线程1");
       thread.start();
       //第二种方式:
       Thread thread = new ThreadCreator();
       thread.start();
       //第三种方式:
       new ThreadCreator().start();
   }
 
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "run");
    }
}

2、实现Runnable接口

(免费学习视频教程分享:java视频教程)

public class ThreadCreator implements Runnable{

    public static void main(String[] args) {
       ThreadCreator creator = new ThreadCreator();
       Thread thread = new Thread(creator,"线程1");
       thread.start();
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "run");
    }
}

3、实现Callable接口

public class ThreadCreator implements Callable {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
       ThreadCreator creator = new ThreadCreator();
       FutureTask futureTask = new FutureTask(creator);
       Thread thread = new Thread(futureTask,"线程");
       thread.start();
       System.out.println(futureTask.get());
    }

    @Override
    public Integer call() {
        return 1024;
    }
}

4、线程池ExecutorService

public class ThreadCreator{

   static ExecutorService service = Executors.newFixedThreadPool(5);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //execute无返回值
        service.execute(new ThreadTask(1,"1"));
        //submit有返回值
        Future result = service.submit(new ThreadTaskCall());
        System.out.println(result.get());
        service.shutdownNow();
    }
    static class ThreadTask implements Runnable{
        private int param1;
        private String param2;
        public ThreadTask(int param3,String param4){
            this.param1 = param3;
            this.param2 = param4;
        }
        @Override
        public void run() {
            System.out.println(param1+param2);
        }
    }

    static class ThreadTaskCall implements Callable{
        @Override
        public Integer call() throws Exception {
            return 1024;
        }
    }
}

线程池中submit和execute的区别:

(1)可接受的任务类型不一样:execute只能接受Runnable任务,submit还可以接受Callable任务。

(2)返回值:execute无返回值,任务一旦提交,无法在当前线程中监控执行结果。submit有一个Future类型的返回值,用来接收返回值或响应异常。通过get()方法获取。

submit底层还是调用的execute,只是在此基础上用future封装了一层,并将执行过程中产生的异常全部封装在一个变量中:

public void run() {
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return;
        try {
            Callable c = callable;
            if (c != null && state == NEW) {
                V result;
                boolean ran;
                try {
                    result = c.call();
                    ran = true;
                } catch (Throwable ex) {
                    result = null;
                    ran = false;
                    setException(ex);
                }
                if (ran)
                    set(result);
            }
        } finally {
            runner = null;
            int s = state;
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
    }
protected void setException(Throwable t) {
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = t;
            UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
            finishCompletion();
        }
    }

另外,spring中的schedule注解借鉴使用了submit的处理方式。

5、匿名内部类

public class ThreadCreator {

    public static void main(String[] args) {

        //继承Thread类
        new Thread() {
            @Override
            public void run() {
                System.out.println("extends Thread Class!");
            }
        }.start();
        //实现Runnable接口
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("implement Runnable!");
            }
        }).start();
        //实现Callable接口
        new Thread(new FutureTask(new Callable() {
            @Override
            public Integer call() throws Exception {
                return 1024;
            }
        })).start();
        //lambda表达式
        new Thread(() -> System.out.println("execute single code")).start();
        new Thread(() -> {
            System.out.println("execute multiple code");
        }).start();
    }
}

lambda线程池:

public class ThreadCreator {

    static ExecutorService service = Executors.newFixedThreadPool(5);

    static List list = new ArrayList();

    public static void main(String[] args) {
        service.execute(() -> execute()); //无返回值
        Future future = service.submit(() -> execute()); //有返回值
        list.add(future);
    }

    public static void execute() {
        //do something
    }
}

以上就是java创建线程的方式汇总,内容较为全面,小编相信有部分知识点可能是我们日常工作可能会见到或用到的。希望你能通过这篇文章学到更多知识。


当前标题:java创建线程的方式有几种?
URL分享:http://bzwzjz.com/article/pdjgdg.html

其他资讯

Copyright © 2007-2020 广东宝晨空调科技有限公司 All Rights Reserved 粤ICP备2022107769号
友情链接: 高端网站设计 营销网站建设 成都网站建设 重庆网站制作 成都网站建设 成都网站设计制作公司 H5网站制作 梓潼网站设计 成都营销网站制作 成都定制网站建设 温江网站设计 成都网站设计 网站建设 网站建设方案 成都h5网站建设 专业网站建设 高端网站设计 成都模版网站建设 成都网站建设公司 成都网站制作 网站制作 成都网站建设公司