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

thread0: a

thread1: b

thread2: c

thread0: d

方案一:轮询

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

答案

import java.util.*;

/**
* n个线程顺序打印英文字母
*/
class Solution {
//用于更换线程
private volatile static int current = 0; public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int in = scanner.nextInt();
int max = 25;
for (int i = 0; i < in; i++) {
new Thread(new Print(in, i, max), "Thread:" + i).start();
}
} static class Print implements Runnable {
//线程总数
private final int num;
//当前线程号
private final int no;
//与current配合更换线程
private final int max; public Print(int num, int no, int max) {
this.num = num;
this.no = no;
this.max = max;
} @Override
public void run() {
while (current <= max) {
if (current % num == no) {
synchronized (Print.class) {
if (current <= max) {
System.out.println(Thread.currentThread().getName() + ":" + (char)(97 + current));
current++;
}
}
}
}
}
} }

测试

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对象进行唤醒。因为每个线程拿到锁以后会做判断,不是他的任务直接就进入等待状态挂起了,所以效率好一些。注意最后判断线程是否要进行挂起的条件,如果之后没有它要进行的任务就不要挂起了,否则最后进程可能执行不完。

import java.util.*;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock; /**
* n个线程顺序打印英文字母
*/
class Solution {
//用于更换线程
private static int current = 0;
private static final ReentrantLock lock = new ReentrantLock();
private static final ArrayList<Condition> conditions = new ArrayList<>(); public static void main(String[] args) {
//输入的数必须大于1
Scanner scanner = new Scanner(System.in);
int in = scanner.nextInt();
int max = 25; //为每个线程设置等待条件
for (int i = 0; i < in; i++) {
conditions.add(lock.newCondition());
} for (int i = 0; i < in; i++) {
new Thread(new Print(in, i, max), "Thread:" + i).start();
}
} static class Print implements Runnable {
//线程总数
private final int num;
//当前线程号
private final int no;
//与current配合更换线程
private final int max; public Print(int num, int no, int max) {
this.num = num;
this.no = no;
this.max = max;
} @Override
public void run() {
while (current <= max) {
try {
lock.lock();
if (current % num == no) {
if (current <= max) {
System.out.println(Thread.currentThread().getName() + ":" + (char)(97 + current));
current++;
}
conditions.get((no + 1) % num).signal();
if (current < max && max - current >= num) {
conditions.get(no).await();
}
} else {
if (current < max && max - current >= num) {
conditions.get(no).await();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
} }
}
}

测试:

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. mybatis 数据搜索后参数显示乱码无法搜到

    今天写作业的时候遇到的小问题 问题说明:搜索订单名中含有"香皂"的订单,显示订单的一系列属性.在搜索后,调试框中显示的东西很奇怪,也没有查找到答案: 觉得是编码问题,所以调试了编码 ...

  2. 51电子-STC89C51开发板:汇编教程

    全部内容请点击目录列表查看: 51电子-STC89C51开发板:<目录> ---------------------------  正文开始  ---------------------- ...

  3. Java基础——IO基础知识

    字节流可以处理任何类型的数据(图片.MP3.视频等文件),字符流只能处理字符类型(文本文件)的数据.

  4. undefined reference to symbol xxxxx和undefined symbol:xxxx错误的原因分析以及解决方法

    Linux下编译程序时,经常会遇到"undefined reference to XXX" 报错,或者运行时出现undefined symbol:xxxx报错. 这里总结一些可能的 ...

  5. C++ STL摘记

    一.string类补充 1.函数示例: (1)find和rfind函数,返回的是下标或者string::npos index=ss.find(s1,pos,num) find从pos(包括)开始往右查 ...

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

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

  7. js 动态给table添加、删除行。

    1.添加table 行 function addtablTr() { var $table = $("#abc"); var vTr = '<tr><td> ...

  8. Flink Application Development DataStream API Execution Mode (Batch/Streaming)- Flink应用程序开发DataStream API执行模式(批/流)

    目录 什么时候可以/应该使用BATCH执行模式? 配置BATCH执行模式 执行行为 任务调度和网络随机shuffle 流执行模式 批处理执行模式 状态后端/状态 处理顺序 Event Time/水印( ...

  9. string 字符串模块操作

    1. 常用方法 2.字符串常量 3.字符串模板Template 通过string.Template可以为Python定制字符串的替换标准,下面是具体列子: >>>from strin ...

  10. android gradle配置及编译command

    build.gradle apply plugin: 'com.android.application' android { compileSdkVersion rootProject.ext.and ...