通过n个线程顺序打印26个英文字母,例如 n=3 则输出:

thread0: a

thread1: b

thread2: c

thread0: d

方案一:轮询

多个线程不断轮询是否是该线程执行任务。因为线程要不断轮循,所以效率较低。

答案

  1. import java.util.*;
  2. /**
  3. * n个线程顺序打印英文字母
  4. */
  5. class Solution {
  6. //用于更换线程
  7. private volatile static int current = 0;
  8. public static void main(String[] args) {
  9. Scanner scanner = new Scanner(System.in);
  10. int in = scanner.nextInt();
  11. int max = 25;
  12. for (int i = 0; i < in; i++) {
  13. new Thread(new Print(in, i, max), "Thread:" + i).start();
  14. }
  15. }
  16. static class Print implements Runnable {
  17. //线程总数
  18. private final int num;
  19. //当前线程号
  20. private final int no;
  21. //与current配合更换线程
  22. private final int max;
  23. public Print(int num, int no, int max) {
  24. this.num = num;
  25. this.no = no;
  26. this.max = max;
  27. }
  28. @Override
  29. public void run() {
  30. while (current <= max) {
  31. if (current % num == no) {
  32. synchronized (Print.class) {
  33. if (current <= max) {
  34. System.out.println(Thread.currentThread().getName() + ":" + (char)(97 + current));
  35. current++;
  36. }
  37. }
  38. }
  39. }
  40. }
  41. }
  42. }

测试

Thread:0:a

Thread:1:b

Thread:2:c

Thread:0:d

Thread:1:e

Thread:2:f

Thread:0:g

Thread:1:h

Thread:2:i

Thread:0:j

Thread:1:k

Thread:2:l

Thread:0:m

Thread:1:n

Thread:2:o

Thread:0:p

Thread:1:q

Thread:2:r

Thread:0:s

Thread:1:t

Thread:2:u

Thread:0:v

Thread:1:w

Thread:2:x

Thread:0:y

Thread:1:z

方案二:condition

对于ReentrantLock,里面提供了newCondition方法,对于每一个线程,其await的时候都可以关联一个Condition对象,别的线程也可以通知这个condition对象进行唤醒。因为每个线程拿到锁以后会做判断,不是他的任务直接就进入等待状态挂起了,所以效率好一些。注意最后判断线程是否要进行挂起的条件,如果之后没有它要进行的任务就不要挂起了,否则最后进程可能执行不完。

  1. import java.util.*;
  2. import java.util.concurrent.locks.Condition;
  3. import java.util.concurrent.locks.ReentrantLock;
  4. /**
  5. * n个线程顺序打印英文字母
  6. */
  7. class Solution {
  8. //用于更换线程
  9. private static int current = 0;
  10. private static final ReentrantLock lock = new ReentrantLock();
  11. private static final ArrayList<Condition> conditions = new ArrayList<>();
  12. public static void main(String[] args) {
  13. //输入的数必须大于1
  14. Scanner scanner = new Scanner(System.in);
  15. int in = scanner.nextInt();
  16. int max = 25;
  17. //为每个线程设置等待条件
  18. for (int i = 0; i < in; i++) {
  19. conditions.add(lock.newCondition());
  20. }
  21. for (int i = 0; i < in; i++) {
  22. new Thread(new Print(in, i, max), "Thread:" + i).start();
  23. }
  24. }
  25. static class Print implements Runnable {
  26. //线程总数
  27. private final int num;
  28. //当前线程号
  29. private final int no;
  30. //与current配合更换线程
  31. private final int max;
  32. public Print(int num, int no, int max) {
  33. this.num = num;
  34. this.no = no;
  35. this.max = max;
  36. }
  37. @Override
  38. public void run() {
  39. while (current <= max) {
  40. try {
  41. lock.lock();
  42. if (current % num == no) {
  43. if (current <= max) {
  44. System.out.println(Thread.currentThread().getName() + ":" + (char)(97 + current));
  45. current++;
  46. }
  47. conditions.get((no + 1) % num).signal();
  48. if (current < max && max - current >= num) {
  49. conditions.get(no).await();
  50. }
  51. } else {
  52. if (current < max && max - current >= num) {
  53. conditions.get(no).await();
  54. }
  55. }
  56. } catch (Exception e) {
  57. e.printStackTrace();
  58. } finally {
  59. lock.unlock();
  60. }
  61. }
  62. }
  63. }
  64. }

测试:

Thread:0:a

Thread:1:b

Thread:2:c

Thread:3:d

Thread:4:e

Thread:0:f

Thread:1:g

Thread:2:h

Thread:3:i

Thread:4:j

Thread:0:k

Thread:1:l

Thread:2:m

Thread:3:n

Thread:4:o

Thread:0:p

Thread:1:q

Thread:2:r

Thread:3:s

Thread:4:t

Thread:0:u

Thread:1:v

Thread:2:w

Thread:3:x

Thread:4:y

Thread:0:z

Process finished with exit code 0

通过n个线程顺序打印26个英文字母的更多相关文章

  1. python3打印26个英文字母

    for a in range(ord('a'), ord('z') + 1): print(chr(a) , end="") for a in range(ord('A'), or ...

  2. Java多个线程顺序打印数字

    要求 启动N个线程, 这N个线程要不间断按顺序打印数字1-N. 将问题简化为3个线程无限循环打印1到3 方法一: 使用synchronized 三个线程无序竞争同步锁, 如果遇上的是自己的数字, 就打 ...

  3. 【多线程基础】- 多个线程顺序打印ABC

    题目:3个线程名字分别是A,B,C 现在在console上连续打印10次 ABC . public class Test { public static void main(String[] args ...

  4. Linux 多线程按照线程顺序打印字符

    #include <stdio.h> #include <pthread.h> #include <unistd.h> ; pthread_mutex_t mute ...

  5. Java小技巧输出26个英文字母

    相信有的童鞋写到过与字母有关的小东西,是否有写过全部的字母呢?26个这么多字母,一个个打会疯掉.所有咱们可以用一个小技巧使用for循环帮我们把26个字母自动搞出来,大家来瞅一眼把! 使用Java遍历2 ...

  6. 利用ascii码生成26个英文字母

    <script> let a = ""; for (var i = 65; i < 91; i++) { a += String.fromCharCode(i); ...

  7. python 一句话输出26个英文字母

    chr(i) # return i character ord(c) # return integer >>> [chr(i) for i in range(97,123)] ['a ...

  8. Java 【打印俄文的英文字母】

    俄文的的字符可以用 'A' 到 'Я '. public class main { public static void main(String args[]) { char S = 'А', C = ...

  9. [No00002A]26个英语字母的原始象形意义、含义、产生及发展历史

    我们都知道汉字是象形文字,但如果说英语也是象形文字,你一定会以为纯是无稽之谈.其实,追根溯源,英语的26个字母确实来自于象形文字.这26个字母最初起源于埃及象形文字,后由腓尼基人改进发明了腓尼基字母, ...

  10. java面试记录二:spring加载流程、springmvc请求流程、spring事务失效、synchronized和volatile、JMM和JVM模型、二分查找的实现、垃圾收集器、控制台顺序打印ABC的三种线程实现

    注:部分答案引用网络文章 简答题 1.Spring项目启动后的加载流程 (1)使用spring框架的web项目,在tomcat下,是根据web.xml来启动的.web.xml中负责配置启动spring ...

随机推荐

  1. element-ui学习之-------input表单验证【各种情况总结】

    1.非必填,正整数 2.非0开头正整数

  2. (一)用go实现单链表

    本篇,我们用go简单的实现单链表这种数据结构. 1.节点定义 type Node struct{ data int next *Node } 2.节点的添加 // 尾插法插入节点 func (p *N ...

  3. 使用go自定义生成项目LISENSE(授权协议)

    需要使用一个使用go开发的工具,叫license,在Windows下安装这个工具,请确保你使用的go sdk是1.16以上的版本,然后执行下面的命令: go install github.com/ni ...

  4. Error occurred while proxying request localhost:端口 报错500的解决方法

    '/AuthServer/api/': { target: 'https://localhost:44319', secure:false,// 这是签名认证,http和https区分的参数设置 ch ...

  5. 【记录】Linux Mint Cinnamon Desktop Enviroment使用记录

    之前使用的系统是Kali Linux,并不是看上了一堆工具,工具的话上虚拟机不好吗,会折腾的docker更好阿,主要是 1. 用习惯了gnome的桌面环境 2. 开箱即用 很多配置他都已经做好了 我都 ...

  6. 攻防世界-easyphp(前导数字字符串、数字字符串、数字弱类型比较)

    一道php代码审计题,利用了字符与数字弱类型比较的漏洞. 一.基础知识 数字字符串 形如数字形式的字符串叫做数字字符串,例如:'123456','1e56112'(科学计数法),'123.4'(单纯的 ...

  7. “adb”不是内部或外部命令——解决方案

    在AS(Android Studio简称AS)app真机测试中adb可以轻松找到安卓设备,ADB全称Android Debug Bridge,用于Android设备进行交互,也可以这样理解ADB是An ...

  8. (转) IIS隐藏响应头信息

    先安装url-rewrite组件 http://www.iis.net/downloads/microsoft/url-rewrite 修改应用根目录下的Web.config配置文件 <conf ...

  9. VS code 安装后gdb调试无法显示STL内容的问题

    bar {...} std::_Vector_base<TSample<MyTraits>, std::allocator<TSample<MyTraits> &g ...

  10. 记录自己在对订单进行按日期查询时使用的一种查询的方法,这里的orders是订单表,你也可以改成别的什么表对于最终数据不会造成影响,除非你那个表的数据只有几条那样就会出现查不到日期的情况

    SELECT @date := DATE_ADD(@date, INTERVAL + 1 DAY) days FROM ( SELECT @date := DATE_ADD("2019-06 ...