首页 文章 精选 留言 我的

精选列表

搜索[AI编程],共10000篇文章
优秀的个人博客,低调大师

【从入门到放弃-Java】并发编程-JUC-ConcurrentLinkedQueue

简介 队列是一种先进先出的数据结构,在排队、削峰、缓存等多种场景下都会用到。今天学习下JUC中提供的并发队列-ConcurrentLinkedQueue可以看他的继承和实现接口非常简单,继承了AbstractQueue类,实现了Queue接口。 ConcurrentLinkedQueue add 在队列尾部新添加一个元素 /** * Inserts the specified element at the tail of this queue. * As the queue is unbounded, this method will never throw * {@link IllegalStateException} or return {@code false}. * * @return {@code true} (as s

优秀的个人博客,低调大师

Java并发编程,深度探索J.U.C - AQS

java.util.concurrent(J.U.C)大大提高了并发性能,AQS 被认为是 J.U.C 的核心。 CountdownLatch用来控制一个线程等待多个线程。 维护了一个计数器 cnt,每次调用 countDown() 方法会让计数器的值减 1,减到 0 的时候,那些因为调用 await() 方法而在等待的线程就会被唤醒。public class CountdownLatchExample { public static void main(String[] args) throws InterruptedException { final int totalThread = 10; CountDownLatch countDownLatch = new CountDownLatch(totalThread); ExecutorService executorService = Executors.newCachedThreadPool(); for (int i = 0; i < totalThread; i++) { executorService.execute(() -> { System.out.print("run.."); countDownLatch.countDown(); }); } countDownLatch.await(); System.out.println("end"); executorService.shutdown(); } }run..run..run..run..run..run..run..run..run..run..endCyclicBarrier用来控制多个线程互相等待,只有当多个线程都到达时,这些线程才会继续执行。 和 CountdownLatch 相似,都是通过维护计数器来实现的。线程执行 await() 方法之后计数器会减 1,并进行等待,直到计数器为 0,所有调用 await() 方法而在等待的线程才能继续执行。 CyclicBarrier 和 CountdownLatch 的一个区别是,CyclicBarrier 的计数器通过调用 reset() 方法可以循环使用,所以它才叫做循环屏障。 CyclicBarrier 有两个构造函数,其中 parties 指示计数器的初始值,barrierAction 在所有线程都到达屏障的时候会执行一次。 public CyclicBarrier(int parties, Runnable barrierAction) { if (parties <= 0) throw new IllegalArgumentException(); this.parties = parties; this.count = parties; this.barrierCommand = barrierAction; } public CyclicBarrier(int parties) { this(parties, null); }public class CyclicBarrierExample { public static void main(String[] args) { final int totalThread = 10; CyclicBarrier cyclicBarrier = new CyclicBarrier(totalThread); ExecutorService executorService = Executors.newCachedThreadPool(); for (int i = 0; i < totalThread; i++) { executorService.execute(() -> { System.out.print("before.."); try { cyclicBarrier.await(); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } System.out.print("after.."); }); } executorService.shutdown(); } }before..before..before..before..before..before..before..before..before..before..after..after..after..after..after..after..after..after..after..after..SemaphoreSemaphore 类似于操作系统中的信号量,可以控制对互斥资源的访问线程数。以下代码模拟了对某个服务的并发请求,每次只能有 3 个客户端同时访问,请求总数为 10。 public class SemaphoreExample { public static void main(String[] args) { final int clientCount = 3; final int totalRequestCount = 10; Semaphore semaphore = new Semaphore(clientCount); ExecutorService executorService = Executors.newCachedThreadPool(); for (int i = 0; i < totalRequestCount; i++) { executorService.execute(()->{ try { semaphore.acquire(); System.out.print(semaphore.availablePermits() + " "); } catch (InterruptedException e) { e.printStackTrace(); } finally { semaphore.release(); } }); } executorService.shutdown(); } } 2 1 2 2 2 2 2 1 2 2

优秀的个人博客,低调大师

熟练掌握Python的内置函数,加快编程速度

内置函数概览 Python 2.7 的所有内置函数共有80个。熟练记住和使用这些内置函数,将大大提高写Python代码的速度和代码的优雅程度。 以下代码示例用的是ipython,一个比官方解释器好很多的解释器,值的学习和使用。 数学相关的内置函数 abs(x) 返回一个数字的绝对值 In [18]: abs(3.14) Out[18]: 3.14 In [19]: abs(-3.14) Out[19]: 3.14 complex(real[, imag]) 生成一个复数 In [135]: complex(1,3) Out[135]: (1+3j) divmod(x, y) 返回x除以y的商和余数 In [143]: divmod(12, 7) Out[143]: (1, 5) max(iterable[, key]) 返回一个序列的最大元素 In [157]: max([(1,2,3), (4,5,6), (23,4,1,)], key=lambda a: a[-1]) Out[157]: (4, 5, 6) In [158]: max(1,2,3,4,4,5) Out[158]: 5 In [159]: max([(1,2,3), (4,5,6), (23,4,1,)]) Out[159]: (23, 4, 1) In [160]: max([(1,2,3), (4,5,6), (23,4,1,)], key=lambda a: a[-1]) Out[160]: (4, 5, 6) In [161]: max([{'age':10, 'name': 'aaa'}, {'age': 12, 'name': 'bb'}], key=lambda a: a['age']) Out[161]: {'age': 12, 'name': 'bb'} min(iterable[, key]) 返回一个序列的最小元素参见上面的max() 函数pow(x, y[, z]) 返回x的y次幂,如果有参数z则返回幂除以z的余数(对z取模) In [166]: pow(2,3) Out[166]: 8 In [167]: pow(2,3,5) Out[167]: 3 round(number[, ndigits]) 返回一个数的四舍五入值,给出ndigits则四舍五入到第n位小数 In [170]: round(3.45) Out[170]: 3.0 In [171]: round(3.55) Out[171]: 4.0 In [172]: round(3.55345, 3) Out[172]: 3.553 sum(sequence[, start]) 对一个数字序列求和,start为起始位置,默认从0开始 In [175]: sum([1,2,3,4]) Out[175]: 10 数字、字符转换 bin(number), hex(number), oct(number) 把一个数字转换成二进制、十六进制、八进制字符串 In [204]: print bin(20), hex(16), oct(9) 0b10100 0x10 011 bool(x) 如果x是真则返回True,否则返回False In [184]: print bool(3), bool('a') True True In [185]: print bool(0), bool(''), bool(None) False False False chr(i) 把一个整数转换ascii码字符, 0<= i < 256 In [188]: chr(320) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-188-5b2996ffe50c> in <module>() ----> 1 chr(320) ValueError: chr() arg not in range(256) In [189]: chr(65) Out[189]: 'A' In [190]: chr(0) Out[190]: '\x00' unichr(i) 把一个整数转换为Unicode字符, 0 <= i <= 0x10ffff In [225]: unichr(1245) Out[225]: u'\u04dd' ord(c) 把一个ascii码字符转换为整数 In [192]: ord('a') Out[192]: 97 In [193]: ord('\x23') Out[193]: 35 float(x), int(x), long(x) 浮点数、整数、长整数之间的转换 In [196]: print float('13'), float(13) 13.0 13.0 In [197]: print int('14'), int(14) 14 14 In [198]: print long('15'), long(15) 15 15 format(value[, format_spec]) 对value按照format_spec格式化 In [212]: format(123, '05d') Out[212]: '00123' 以上等同于 print ‘%05d’ % 123 hash(ojbect) 对object计算hash值 In [218]: hash(123) Out[218]: 123 In [219]: hash('abc') Out[219]: 1453079729188098211 str(object=’’) 把一个对象转换成字符串: In [221]: str(123) Out[221]: '123' In [222]: str([1,2,3]) Out[222]: '[1, 2, 3]' In [223]: str({'a': 1, 'b': 2}) Out[223]: "{'a': 1, 'b': 2}" 输入输出 file(name[, mode[, buffering]]), open 打开一个文件 In [251]: file('abc.txt', 'w') Out[251]: <open file 'abc.txt', mode 'w' at 0x7f93e727a660> In [252]: open('abc.txt', 'w') Out[252]: <open file 'abc.txt', mode 'w' at 0x7f93e727a780> input([prompt]), raw_input() 从终端输入信息 In [253]: input('pls input a number >>') pls input a number >>123 Out[253]: 123 序列处理 all(iterable) 如果一个序列所有值都为真就返回True,否则返回Falseany(iterable) 如果一个序列至少有一个为真就返回True, 否则False In [255]: all([1,2,3,4]) Out[255]: True In [256]: all([1,2,3,4, 0]) Out[256]: False In [257]: any([1,2,3,4, 0]) Out[257]: True enumerate(iterable[, start]) 遍历一个序列的元素及其索引 In [261]: for i, value in enumerate(['a', 'b', 'c']): .....: print i, value .....: 0 a 1 b 2 c filter(function or None, squence) 返回满足function(item)为True的元素 In [263]: filter(lambda x: x>3, [1,2,3,4,5]) Out[263]: [4, 5] iter(collection) 返回一个对象的迭代器读取文件的时候比较有用: with open("mydata.txt") as fp: for line in iter(fp.readline, "STOP"): process_line(line) len(object) 返回一个对象的元素个数 In [267]: len('abc'), len([1,2,3]) Out[267]: (3, 3) map(function, sequence[, sequence, …]) 把一个函数应用于每一个元素并返回一个list In [269]: map(lambda x: x+3, [1,2,3]) Out[269]: [4, 5, 6] In [270]: a = [1,2]; b = ['a', 'b']; c = ('x', 'y') In [271]: map(None, a, b, c) Out[271]: [(1, 'a', 'x'), (2, 'b', 'y')] reduce(function, sequence[, sequence, …]) 把函数作用于初始两个元素,并把返回值和下一个元素作为输入调用函数,依次迭代所有元素 In [281]: reduce(lambda a, b: a-b, [1,2,3]) Out[281]: -4 zip(seq1 [, seq2 […]]) -> [(seq1[0], seq2[0] …), (…)] 把多个序列合并成一个序列list In [283]: zip([1,2,3], ('a', 'b', 'c')) Out[283]: [(1, 'a'), (2, 'b'), (3, 'c')] range() xrange() 返回一个整数序列 In [274]: [x for x in xrange(10)] Out[274]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] In [275]: [x for x in xrange(5, 10)] Out[275]: [5, 6, 7, 8, 9] In [276]: [x for x in xrange(5, 10, 2)] Out[276]: [5, 7, 9] In [277]: range(10) Out[277]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] In [278]: range(5, 10) Out[278]: [5, 6, 7, 8, 9] In [279]: range(5, 10, 2) Out[279]: [5, 7, 9] sorted(iterable, cmp=None, key=None, reverse=False) 对一个序列排序可选参数cmp、key和reverse与list.sort()方法的参数含义相同(在可变的序列类型一节描述)。cmp指定一个自定义的带有两个参数的比较函数(可迭代的元素),它应该根据第一个参数是小于、等于还是大于第二个参数返回负数、零或者正数:cmp=lambda x,y: cmp(x.lower(), y.lower())。默认值是None。key指定一个带有一个参数的函数,它用于从每个列表元素选择一个比较的关键字:key=str.lower。默认值是None(直接比较元素)。reverse是一个布尔值。如果设置为True,那么列表元素以反向比较排序。通常情况下,key和reverse转换处理比指定一个等同的cmp函数要快得多。这是因为cmp为每个元素调用多次但是key和reverse只会触摸每个元素一次。使用functools.cmp_to_key()来转换旧式的cmp函数为key函数。 In [288]: sorted(d.items(), key=lambda a: a[1]) Out[288]: [('a', 3), ('b', 4)] In [289]: sorted(d.items(), key=lambda a: a[1], rev) In [289]: sorted(d.items(), key=lambda a: a[1], reverse=True) Out[289]: [('b', 4), ('a', 3)] In [290]: sorted(d.items(), cmp=lambda a, b: cmp(a[1], b[1])) Out[290]: [('a', 3), ('b', 4)] 数据结构 bytearray() dict() frozenset() list() set() tuple()python里面常用的数据结构有列表(list)、字典(dict)、集合(set)、元组(tuple) 对象、类型 以下是一些类(class)和类型相关的函数,比较不常用,可以查看手册详细了解。basestring() callable() classmethod() staticmethod() property() cmp() compile() delattr() getattr() setattr() hasattr() dir() globals() locals() vars() help() id() isinstance() issubclass() object() memoryview() repr() super() type() unicode() import() eval() execfile() 不重要的内置函数 apply() buffer() coerce() intern() ipython ipython是一个非常好的交互式python解释器,它查看一个函数或类的用法的方法有: help(xxx)xxx?查看一个类/对象的成员函数或变量时,在类或对象变量后面输入.后按tab键: In [292]: import time In [293]: time. time.accept2dyear time.clock time.gmtime time.sleep time.struct_time time.tzname time.altzone time.ctime time.localtime time.strftime time.time time.tzset time.asctime time.daylight time.mktime time.strptime time.timezone In [293]: time.ti time.time time.timezone In [293]: time.time? Docstring: time() -> floating point number Return the current time in seconds since the Epoch. Fractions of a second may be present if the system clock provides them. Type: builtin_function_or_method 版权申明:若没有特殊说明,文章皆是猿人学原创,没有猿人学授权,请勿以任何形式转载。

资源下载

更多资源
Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

腾讯云软件源

腾讯云软件源

为解决软件依赖安装时官方源访问速度慢的问题,腾讯云为一些软件搭建了缓存服务。您可以通过使用腾讯云软件源站来提升依赖包的安装速度。为了方便用户自由搭建服务架构,目前腾讯云软件源站支持公网访问和内网访问。

Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Sublime Text

Sublime Text

Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。

用户登录
用户注册