zoukankan      html  css  js  c++  java
  • 多线程同步

     并发,与并行这个问题,估计网络上的人写得也不是很对。

    并行,是确实物理上,多个任务被同时执行。举例子,多个CPU就可以实现,多个任务在不同的CPU同时处理。

    并发,是多个任务都得到了处理,但是不是保证是在同一时刻。举例子,多线程在一个核里面进行调度,切换上下文,执行不同的任务,由于表面上看响应速度加快了,貌似任务同时执行,这个就是并发,虽然实际还是轮流执行,但是这个不关心你具体是如何实现的。

    好多人都问,多线程如何处理同步互斥问题?在思考这个问题之前,不妨看看段文字。

    1.不要自己手动创建线程,因为第一有保证,第二能管理,CGD就是一种thread pool的机制,能管理线程,好处就是避免重复创建线程,控制线程数量,控制线程的调度。 

    Avoid Creating Threads Explicitly

    Writing thread-creation code manually is tedious and potentially error-prone and you should avoid it whenever possible. OS X and iOS provide implicit support for concurrency through other APIs. Rather than create a thread yourself, consider using asynchronous APIs, GCD, or operation objects to do the work. These technologies do the thread-related work behind the scenes for you and are guaranteed to do it correctly. In addition, technologies such as GCD and operation objects are designed to manage threads much more efficiently than your own code ever could by adjusting the number of active threads based on the current system load. For more information about GCD and operation objects, see Concurrency Programming Guide.

    2. 避免共享数据, 最简单的方法就是复制一份。简单就是美。多线程就算你非常仔细在每个关键节点加上lock,你的代码还是不是安全的。把代码改为基于事务的模型可以抵得上多线程的性能优势。

    Avoid Shared Data Structures

    The simplest and easiest way to avoid thread-related resource conflicts is to give each thread in your program its own copy of whatever data it needs. Parallel code works best when you minimize the communication and resource contention among your threads.

    Creating a multithreaded application is hard. Even if you are very careful and lock shared data structures at all the right junctures in your code, your code may still be semantically unsafe. For example, your code could run into problems if it expected shared data structures to be modified in a specific order. Changing your code to a transaction-based model to compensate could subsequently negate the performance advantage of having multiple threads. Eliminating the resource contention in the first place often results in a simpler design with excellent performance.

  • 相关阅读:
    SpringBoot条件注解@Conditional
    IDEA远程Debug
    聊一聊Java如何接入招行一网通支付功能
    IDEA中使用lombok插件
    使用Java类加载SpringBoot、SpringCloud配置文件
    Java项目启动时执行指定方法的几种方式
    Java定时任务解决方案
    04 Python并发编程(守护进程,进程锁,进程队列)
    03 初识并发编程
    02 网络编程协议(TCP和UDP协议,黏包问题)以及socketserver模块
  • 原文地址:https://www.cnblogs.com/studyNT/p/8384429.html
Copyright © 2011-2022 走看看