通过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 ...
随机推荐
- element-ui学习之-------input表单验证【各种情况总结】
1.非必填,正整数 2.非0开头正整数
- (一)用go实现单链表
本篇,我们用go简单的实现单链表这种数据结构. 1.节点定义 type Node struct{ data int next *Node } 2.节点的添加 // 尾插法插入节点 func (p *N ...
- 使用go自定义生成项目LISENSE(授权协议)
需要使用一个使用go开发的工具,叫license,在Windows下安装这个工具,请确保你使用的go sdk是1.16以上的版本,然后执行下面的命令: go install github.com/ni ...
- Error occurred while proxying request localhost:端口 报错500的解决方法
'/AuthServer/api/': { target: 'https://localhost:44319', secure:false,// 这是签名认证,http和https区分的参数设置 ch ...
- 【记录】Linux Mint Cinnamon Desktop Enviroment使用记录
之前使用的系统是Kali Linux,并不是看上了一堆工具,工具的话上虚拟机不好吗,会折腾的docker更好阿,主要是 1. 用习惯了gnome的桌面环境 2. 开箱即用 很多配置他都已经做好了 我都 ...
- 攻防世界-easyphp(前导数字字符串、数字字符串、数字弱类型比较)
一道php代码审计题,利用了字符与数字弱类型比较的漏洞. 一.基础知识 数字字符串 形如数字形式的字符串叫做数字字符串,例如:'123456','1e56112'(科学计数法),'123.4'(单纯的 ...
- “adb”不是内部或外部命令——解决方案
在AS(Android Studio简称AS)app真机测试中adb可以轻松找到安卓设备,ADB全称Android Debug Bridge,用于Android设备进行交互,也可以这样理解ADB是An ...
- (转) IIS隐藏响应头信息
先安装url-rewrite组件 http://www.iis.net/downloads/microsoft/url-rewrite 修改应用根目录下的Web.config配置文件 <conf ...
- VS code 安装后gdb调试无法显示STL内容的问题
bar {...} std::_Vector_base<TSample<MyTraits>, std::allocator<TSample<MyTraits> &g ...
- 记录自己在对订单进行按日期查询时使用的一种查询的方法,这里的orders是订单表,你也可以改成别的什么表对于最终数据不会造成影响,除非你那个表的数据只有几条那样就会出现查不到日期的情况
SELECT @date := DATE_ADD(@date, INTERVAL + 1 DAY) days FROM ( SELECT @date := DATE_ADD("2019-06 ...