栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java 多线程,并发编程

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java 多线程,并发编程

一、创建线程有几种方式

看了好多博文,都说三种或者三种之上的,其实本质只有两种,有Java源码Thread类的上面的注释为证:

There are two ways to create a new thread of execution. One is to declare a class to be a subclass of Thread.
...
The other way to create a thread is to declare a class that implements the Runnable interface. 
1.列举一下大多数博文所说的四种创建线程的方式 (1).继承使用Thread类
public class MyThread extends Thread{
    //重写run方法
    @Override
    public void run() {
        System.out.println("继承Thread类创建线程");
    }
 
    public static void main(String[] args) {
        //创建继承Thread类的对象调用start方法来启动线程
        MyThread mythread = new MyThread ();
        MyThread .start();
    }
}
(2).实现Runnable接口
public class MyThread implements Runnable{
    //重写run方法
    @Override
    public void run() {
        System.out.println("实现Runnable接口创建线程");
    }
 
    public static void main(String[] args) {
        //创建实现Runnable接口的类的对象
        MyThread mythread= new MyThread ();
        //使用Thread类的匿名对象调用start方法
        new Thread(mythread).start();
    }
}

发现其实本质还是使用Thread类,只不过线程执行的代码的位置不同。

(3).实现Callable接口

上面两种最古老基本的基本用法不在多说,这个Callable平时不常用这里重点讲一下

1).使用FutureTask,交给线程池执行,阻塞等待结果返回

public class UseCallableCreateThread implements Callable {

    @Override
    public String call() throws Exception {
        Thread.sleep(3000L);
        System.out.println("当前线程:" + Thread.currentThread().getName());
        return "执行完毕";
    }

    public static void main(String[] args) {
        System.out.println("主线程:" + Thread.currentThread().getName());
        FutureTask futureTask = new FutureTask(new UseCallableCreateThread());
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        System.out.println("开始时间戳为:" + System.currentTimeMillis());
        executorService.submit(futureTask);
        String result = null;
        try {
            result = futureTask.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        } finally {
            executorService.shutdown();
        }
        System.out.println("结束时间戳为:" + System.currentTimeMillis() + ",result = " + result);
    }
}

执行结果:

主线程:main
开始时间戳为:1653986152199
当前线程:pool-1-thread-1
结束时间戳为:1653986155204,result = 执行完毕

可以看到开启了一个新的线程,并且主线程通过阻塞式接受异步线程返回的内容。

2).如果直接调用futureTask的run方法会怎样?

public class UseCallableCreateThread implements Callable {

    @Override
    public String call() throws Exception {
        Thread.sleep(3000L);
        System.out.println("当前线程:" + Thread.currentThread().getName());
        return "执行完毕";
    }

    public static void main(String[] args) {
        System.out.println("主线程:" + Thread.currentThread().getName());
        FutureTask futureTask = new FutureTask(new UseCallableCreateThread());
        System.out.println("开始时间戳为:" + System.currentTimeMillis());
        String result = null;
        try {
            futureTask.run();
            result = futureTask.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println("结束时间戳为:" + System.currentTimeMillis() + ",result = " + result);
    }
}

执行结果:

主线程:main
开始时间戳为:1653990338855
当前线程:main
结束时间戳为:1653990341856,result = 执行完毕

并没有开启线程,只是执行了Callable中的call方法。

3).通过线程池执行,返回Future对象

public class UseCallableCreateThread implements Callable {

    @Override
    public String call() throws Exception {
        Thread.sleep(3000L);
        System.out.println("当前线程:" + Thread.currentThread().getName());
        return "执行完毕";
    }

    public static void main(String[] args) {
        System.out.println("主线程:" + Thread.currentThread().getName());
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        System.out.println("开始时间戳为:" + System.currentTimeMillis());
        Future future = executorService.submit(new UseCallableCreateThread());
        String result = null;
        try {
            result = future.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        } finally {
            executorService.shutdown();
        }
        System.out.println("结束时间戳为:" + System.currentTimeMillis() + ",result = " + result);
    }
}

执行结果:

主线程:main
开始时间戳为:1653991286480
当前线程:pool-1-thread-1
结束时间戳为:1653991289484,result = 执行完毕

可以看到也是开启了一个线程,并且主线程通过阻塞式接受异步线程返回的内容,这个用法的实质和第一个没有区别,这个返回的Future就是FutureTask:

从源码看问题:

1).为什么第一种和第三种本质一样

    public Future submit(Runnable task) {
        if (task == null) throw new NullPointerException();
        RunnableFuture ftask = newTaskFor(task, null);
        execute(ftask);
        return ftask;
    }

    public  Future submit(Callable task) {
        if (task == null) throw new NullPointerException();
        RunnableFuture ftask = newTaskFor(task);
        execute(ftask);
        return ftask;
    }

    protected  RunnableFuture newTaskFor(Callable callable) {
        return new FutureTask(callable);
    }

从源码中可以看到无论是传的Runnable(FutureTask)还是Callable最后都会生成一个FutureTask执行execute方法和作为返回值返回。

关于线程池下面分析。

2).future.get方法如何阻塞等待异步线程执行结果

    private volatile int state;
    private static final int NEW          = 0;
    private static final int COMPLETING   = 1;
    private static final int NORMAL       = 2;
    private static final int EXCEPTIONAL  = 3;
    private static final int CANCELLED    = 4;
    private static final int INTERRUPTING = 5;
    private static final int INTERRUPTED  = 6;


    public V get() throws InterruptedException, ExecutionException {
        int s = state;
        if (s <= COMPLETING)
            // 如果状态还在进行中,或者刚创建,就阻塞等待
            s = awaitDone(false, 0L);
        // 调用Report,返回结果或者抛出异常
        return report(s);
    }

    private V report(int s) throws ExecutionException {
        Object x = outcome;
        if (s == NORMAL)
            // 状态正常,返回结果
            return (V)x;
        if (s >= CANCELLED)
            // 状态取消,抛出取消异常
            throw new CancellationException();
        // 抛出程序执行异常
        throw new ExecutionException((Throwable)x);
    }

awaitDone方法阻塞的线程,这个方法比较复下面分析。FutureTask内部维护了任务进行的状态,当异步任务完成时,会将状态码设置为已完成,如果发生异常,会将状态码设置成对应的异常状态码。

3).自己用Runnable实现一个有返回值的,还阻塞主线程的功能。

public class HadedResultRunnable implements Runnable{

    private String result;

    private AtomicBoolean finished = new AtomicBoolean(); //并发下的boolean类型使用CAS 和 volatile保证并发安全

    public void run() {
        try {
            Thread.sleep(3000L);
            System.out.println("当前线程:" + Thread.currentThread().getName());
            this.result = "hello world";
            finished.compareAndSet(false, true); // 执行完了就改变flag
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public String get() {
        while (true) {
            if (finished.get()) {
                return result;
            }
        }
    }

    public static void main(String[] args) throws Exception {
        System.out.println("开始时间戳为:" + System.currentTimeMillis());
        HadedResultRunnable myRunnable = new HadedResultRunnable();
        new Thread(myRunnable).start();
        String result = myRunnable.get();
        System.out.println("结束时间戳为:" + System.currentTimeMillis() + ",result = " + result);
    }
}

分析一下FutureTask和Callable:

(4).使用线程池

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/939352.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号