通过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 ...
随机推荐
- windows安装和重装系统后无法识别U盘
安装系统的方法: 1. 方案一,用大白菜制写入pe系统,但必须先准备Windows安装包 方案二,把ISO格式的系统安装包直接写入到u盘,写入U盘的方法请百度 2.开机看到电脑的logo后,按f2(不 ...
- Android GNSS模块详解
1. 参考https://blog.csdn.net/yang_mao_shan/category_12133410.html GNSS 架构是从 应用层 ---> 通过原生 jar 包 --- ...
- 《Makefile中DEP_LIBRARIES变量的作用》
1.例子 DEP_LIBRARIES := lib@InfoSDK_api lib@WMTMedia lib@WMTUtil lib@curl 该变量是Makefile里面内置的变量,作用是指定依赖的 ...
- springboot gradle 集成流程引擎activiti
buildscript { repositories { maven { url 'https://maven.aliyun.com/repository/gradle-plugin' } } dep ...
- 读后笔记 -- Python 全栈测试开发 Chapter11:Python + Requests 实现接口测试
11.1 Requests 框架 11.1.1 requests 请求 1. reqeusts 库 安装 pip install requests 2. requests 库 GET 方法,参数通过 ...
- 攻防世界-easyphp(前导数字字符串、数字字符串、数字弱类型比较)
一道php代码审计题,利用了字符与数字弱类型比较的漏洞. 一.基础知识 数字字符串 形如数字形式的字符串叫做数字字符串,例如:'123456','1e56112'(科学计数法),'123.4'(单纯的 ...
- Oracle虚拟机与主机共享设置
VM中linux与主机的文件共享 1.打开 Oracle VM VirtualBox 点击 [控制] [设置] [数据空间] 添加你所希望共享的文件夹
- Office常见问题及解决方法
1.OneNote粘贴的图片比较模糊 问题原因:Microsoft为了使OneNote排版美观,在粘贴一些尺寸较大的图片时,会将图片进行缩放. 解决方法:右键->还原为原始尺寸
- 吴恩达老师机器学习课程chapter05——评估模型
吴恩达老师机器学习课程chapter05--评估模型 本文是非计算机专业新手的自学笔记,高手勿喷. 本文仅作速查备忘之用,对应吴恩达(AndrewNg)老师的机器学期课程第十章.第十一章. 目录 吴恩 ...
- 不安全的权限 0644,建议使用 0600 虚拟机无法分配内存 virtual memory exhausted: Cannot allocate memory
我都不知道我写了啥,自己都很混乱 aoteman@aoteman-virtual-machine:/tmp$ sudo -s #进入root用户模式 [sudo] aoteman 的密码: 12对不起 ...