美文网首页我爱编程
第三十六节 协程

第三十六节 协程

作者: 最美下雨天 | 来源:发表于2018-06-03 18:04 被阅读56次

什么是携程?
引述一段博客(来自https://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/0013868328689835ecd883d910145dfa8227b539725e5ed000
协程,又称微线程,纤程。英文名Coroutine。

协程的概念很早就提出来了,但直到最近几年才在某些语言(如Lua)中得到广泛应用。

子程序,或者称为函数,在所有语言中都是层级调用,比如A调用B,B在执行过程中又调用了C,C执行完毕返回,B执行完毕返回,最后是A执行完毕。

所以子程序调用是通过栈实现的,一个线程就是执行一个子程序。

子程序调用总是一个入口,一次返回,调用顺序是明确的。而协程的调用和子程序不同。

协程看上去也是子程序,但执行过程中,在子程序内部可中断,然后转而执行别的子程序,在适当的时候再返回来接着执行。

注意,在一个子程序中中断,去执行其他子程序,不是函数调用,有点类似CPU的中断。比如子程序A、B:

def A():
    print '1'
    print '2'
    print '3'

def B():
    print 'x'
    print 'y'
    print 'z'

假设由协程执行,在执行A的过程中,可以随时中断,去执行B,B也可能在执行过程中中断再去执行A,结果可能是:

1
2
x
y
3
z

但是在A中是没有调用B的,所以协程的调用比函数调用理解起来要难一些。

看起来A、B的执行有点像多线程,但协程的特点在于是一个线程执行,那和多线程比,协程有何优势?

最大的优势就是协程极高的执行效率。因为子程序切换不是线程切换,而是由程序自身控制,因此,没有线程切换的开销,和多线程比,线程数量越多,协程的性能优势就越明显。

第二大优势就是不需要多线程的锁机制,因为只有一个线程,也不存在同时写变量冲突,在协程中控制共享资源不加锁,只需要判断状态就好了,所以执行效率比多线程高很多。

因为协程是一个线程执行,那怎么利用多核CPU呢?最简单的方法是多进程+协程,既充分利用多核,又充分发挥协程的高效率,可获得极高的性能

kotlin中的协程

官网:http://kotlinlang.org/docs/reference/
参考文档:http://johnnyshieh.me/posts/kotlin-coroutine-introduction/
学习协程之前,先来看几个知识点

  • 普通线程与守护线程
    setDaemon(boolean on)
    将该线程标记为守护线程或用户线程。当正在运行的线程都是守护线程时,Java 虚拟机退出。
    该方法必须在启动线程前调用。
  • 线程池
  • join() 等待该线程终止

守护线程

先来看个简单的例子

public class ThreadDemo {

    public static void main(String[] args)
    {
        System.out.println("我是主线程开始了");
        new Thread(new MyRunnable()).start();
        System.out.println("我是主线程结束了");

    }
}
public class MyRunnable implements Runnable {
    private int i=0;
    @Override
    public void run() {

        boolean flag=true;
        while(flag)
        {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("第" + i + "个数字");
            i++;
            if(i>=10)
            {
                flag=false;
            }

        }
    }
}

运行结果:
打印出了预期的结果,而且运行完成后程序退出了


image.png

修改代码:

public class ThreadDemo {

    public static void main(String[] args)
    {
        System.out.println("我是主线程开始了");
        Thread thread=new Thread(new MyRunnable());
        thread.setDaemon(true);
        thread.start();
        System.out.println("我是主线程结束了");

    }
}

运行结果:


image.png

我们让主线程休眠一秒钟

public class ThreadDemo {

    public static void main(String[] args)
    {
        System.out.println("我是主线程开始了");
        Thread thread=new Thread(new MyRunnable());
        thread.setDaemon(true);
        thread.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("我是主线程结束了");

    }
}

运行结果:


image.png

当我们把一个线程设置为守护线程时,这个线程会随着主线程的结束而结束

join()

修改代码:在主线程结束之前调用join方法

public class ThreadDemo {

    public static void main(String[] args)
    {
        System.out.println("我是主线程开始了");
        Thread thread=new Thread(new MyRunnable());
        thread.setDaemon(true);
        thread.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("我是主线程结束了");

        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

输出:


image.png

线程池

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadDemo {

    public static void main(String[] args)
    {
        System.out.println("我是主线程开始了");
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        executorService.execute(new MyRunnable());
        System.out.println("我是主线程结束了");

    }
}

运行结果:


image.png

kotlin中的协程

github地址:https://github.com/Kotlin/kotlinx.coroutines

import kotlinx.coroutines.experimental.launch

fun main(args: Array<String>) {

    println("主线程开始执行了")
    launch {
        println("我是协程")
    }
    println("主线程结束了")

}

运行结果:


image.png

让主线程睡眠一秒钟

import kotlinx.coroutines.experimental.launch

fun main(args: Array<String>) {

    println("主线程开始执行了")
    launch {
        println("我是协程序")
    }
    println("主线程结束了")
    Thread.sleep(1000)

}

运行结果:


image.png

有没有感觉这个跟前面的守护线程是一样的效果呢

launch函数

我们看下launch这个函数的声明

public actual fun launch(
    context: CoroutineContext = DefaultDispatcher,
    start: CoroutineStart = CoroutineStart.DEFAULT,
    parent: Job? = null,
    block: suspend CoroutineScope.() -> Unit
): Job {
    val newContext = newCoroutineContext(context, parent)
    val coroutine = if (start.isLazy)
        LazyStandaloneCoroutine(newContext, block) else
        StandaloneCoroutine(newContext, active = true)
    coroutine.start(start, coroutine, block)
    return coroutine
}

launch函数有四个参数,前三个都有默认值,调用的时候可以省略,第四个参数是个lambda表达式,它的返回值是Job类型
仔细看下第一个参数(协程上下文)

context: CoroutineContext = DefaultDispatcher
public actual val DefaultDispatcher: CoroutineDispatcher = CommonPool
//是个单例,继承了CoroutineDispatcher
object CommonPool : CoroutineDispatcher() {


//省略很多


private fun createPool(): ExecutorService {
        if (System.getSecurityManager() != null) return createPlainPool()
        val fjpClass = Try { Class.forName("java.util.concurrent.ForkJoinPool") }
            ?: return createPlainPool()
        if (!usePrivatePool) {
            Try { fjpClass.getMethod("commonPool")?.invoke(null) as? ExecutorService }
                ?.let { return it }
        }
        Try { fjpClass.getConstructor(Int::class.java).newInstance(defaultParallelism()) as? ExecutorService }
            ?. let { return it }
        return createPlainPool()
    }


//省略很多


}

关于这个类的描述

If there isn't a SecurityManager present it uses [java.util.concurrent.ForkJoinPool] when available

ForkJoinPool就是个线程池,而且线程池中的线程是守护线程,launch函数的第一个参数就是指定协程要运行的线程、线程池
我们也可以单独使用下ForkJoinPool

import java.util.concurrent.ForkJoinPool

fun main(args: Array<String>) {

    println("主线程开始执行了")
    val forkJoinPool = ForkJoinPool(3)

    forkJoinPool.execute(MyRunnable())
    println("主线程结束了")
    Thread.sleep(1000)

}

输出:


image.png

我们在协程中做个耗时操作

import kotlinx.coroutines.experimental.launch

fun main(args: Array<String>) {

    println("主线程开始执行了")

    launch {
        (1..10).forEach {
            println("协程打印第${it}个数字")
            Thread.sleep(500)
        }
    }
    println("主线程结束了")
    Thread.sleep(1000)


}

输出:


image.png

跟前面的守护线程一样,主线程结束后协程也结束了
修改代码:

import kotlinx.coroutines.experimental.launch
import kotlinx.coroutines.experimental.runBlocking

fun main(args: Array<String>) = runBlocking{

    println("主线程开始执行了")

    val la = launch {
        (1..10).forEach {
            println("协程打印第${it}个数字")
            Thread.sleep(500)
        }
    }
    println("主线程结束了")
    Thread.sleep(1000)

    la.join()


}

输出:


image.png

相关文章

网友评论

    本文标题:第三十六节 协程

    本文链接:https://www.haomeiwen.com/subject/zkcdsftx.html