通过n个线程顺序打印26个英文字母
通过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个英文字母的更多相关文章
- python3打印26个英文字母
for a in range(ord('a'), ord('z') + 1): print(chr(a) , end="") for a in range(ord('A'), or ...
- Java多个线程顺序打印数字
要求 启动N个线程, 这N个线程要不间断按顺序打印数字1-N. 将问题简化为3个线程无限循环打印1到3 方法一: 使用synchronized 三个线程无序竞争同步锁, 如果遇上的是自己的数字, 就打 ...
- 【多线程基础】- 多个线程顺序打印ABC
题目:3个线程名字分别是A,B,C 现在在console上连续打印10次 ABC . public class Test { public static void main(String[] args ...
- Linux 多线程按照线程顺序打印字符
#include <stdio.h> #include <pthread.h> #include <unistd.h> ; pthread_mutex_t mute ...
- Java小技巧输出26个英文字母
相信有的童鞋写到过与字母有关的小东西,是否有写过全部的字母呢?26个这么多字母,一个个打会疯掉.所有咱们可以用一个小技巧使用for循环帮我们把26个字母自动搞出来,大家来瞅一眼把! 使用Java遍历2 ...
- 利用ascii码生成26个英文字母
<script> let a = ""; for (var i = 65; i < 91; i++) { a += String.fromCharCode(i); ...
- python 一句话输出26个英文字母
chr(i) # return i character ord(c) # return integer >>> [chr(i) for i in range(97,123)] ['a ...
- Java 【打印俄文的英文字母】
俄文的的字符可以用 'A' 到 'Я '. public class main { public static void main(String args[]) { char S = 'А', C = ...
- [No00002A]26个英语字母的原始象形意义、含义、产生及发展历史
我们都知道汉字是象形文字,但如果说英语也是象形文字,你一定会以为纯是无稽之谈.其实,追根溯源,英语的26个字母确实来自于象形文字.这26个字母最初起源于埃及象形文字,后由腓尼基人改进发明了腓尼基字母, ...
- java面试记录二:spring加载流程、springmvc请求流程、spring事务失效、synchronized和volatile、JMM和JVM模型、二分查找的实现、垃圾收集器、控制台顺序打印ABC的三种线程实现
注:部分答案引用网络文章 简答题 1.Spring项目启动后的加载流程 (1)使用spring框架的web项目,在tomcat下,是根据web.xml来启动的.web.xml中负责配置启动spring ...
随机推荐
- 南大ics-pa/PA1.1过程及感想
1.1 一.在红白模拟器上运行超级马里奥游戏 1.将游戏rom文件mario.nes移至~/ics2022/fceux-am/nes/rom文件下,并回到~/ics2022/fceux-am下执行ma ...
- 关于sqlyang 连接远程服务器 MySQL "1251-client does not support authentication..."的处理办法
原因是在mysql8之前的版本中加密规则为mysql_native_password而在mysql8以后的加密规则为caching_sha2_password. 做如下修改 ALTER USER 'r ...
- Linux下安装MongoDB的Database Tools并配置
安装tools以使用导入导出功能.解决mongodump: command not found #下载 wget https://fastdl.mongodb.org/tools/db/mongodb ...
- Chart控件-常用设置
visual studio中原生控件chart控件使用时的一些常用设置 鼠标缩放功能 缩放后恢复曲线
- 【服务器数据恢复】HP EVA存储多块硬盘离线的数据恢复案例
服务器故障&检测&分析:某品牌EVA存储设备中的RAID5磁盘有两块硬盘掉线,lun丢失.硬件工程师对故障服务器进行物理故障检测,发现掉线硬盘能够正常读取,无物理故障,也没有发现坏道. ...
- TIDB-DM数据迁移第三部(集群管理)
1.对现在 dm 集群进行缩容,将 free 状态的 worker 下线. tiup dm display dm-test 查看 free 状态节点 tiup dm scale-in dm 172.1 ...
- linux 安装goland
一.Goland-IDEA 2020.3.2安装 1 下载 下载GoLand https://www.jetbrains.com/go/download/#section=linux 2 安装Gola ...
- composer disgnoize public key fail
https://composer.github.io/pubkeys.html 还有这事, 太不可思议了哦.--怎么进去的, 真的不知道哦.
- Python——02.变量及标识符
变量概念: -- 字面量:与字面上显示值一致的量称作字面量,在程序中可直接使用字面量:abc,123, 我是XX,等等 -- 变量:变量可通过赋值保存字面量,变量是可变的,跟随赋值的字面量不同而变化 ...
- Java script Date和长整型互换
document.write(new Date().getTime()); document.write('<br/>') var date1=new Date(1590024428000 ...