题目:
打字练习 随机生成一个字符串 让用户进行输入 10秒钟内输入正确就通过 否则不通过
Seelp类(控制10秒时间限制)
package com.sy.day04.work;
/**
* @Author: ShenYang
* @Date: 2023-06-15-16:37
* @Description: TODO
* <p>
* comment:
**/
public class Seelp implements Runnable{
@Override
public void run() {
try {
Thread.sleep(10000);
System.out.println("\n 10秒时间到,未通过!");
System.exit(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
Work_01类(3个线程生成字母组合字符串)
package com.sy.day04.work_01;
import java.util.Random;
/**
* @Author: ShenYang
* @Date: 2023-06-15-16:10
* @Description: TODO
* <p>
* comment:
**/
public class Work_01 implements Runnable {
static int len;
static String str="";
static Object object = new Object();
@Override
public void run() {
Random random = new Random();
while (true) {
synchronized (object){
if (len > 0) {
int i = random.nextInt(26) + 97;
str +=(char) i;
len--;
} else {
return;
}
}
}
}
}
Test类(work_01方法中创建三个线程生成字符串, main方法启动Seelp)
package com.sy.day04.work;
import java.util.Objects;
import java.util.Random;
import java.util.Scanner;
/**
* @Author: ShenYang
* @Date: 2023-06-15-16:09
* @Description: TODO
* <p>
* comment:
* 1.打字练习 随机生成一个字符串 让用户进行输入 10秒钟内输入正确就通过 否则不通过
* 2.多线程按顺序打印10次ABC
**/
public class Test_01 {
public static void main(String[] args) throws InterruptedException {
Seelp seelp = new Seelp();
Scanner scanner = new Scanner(System.in);
System.out.println("请在10秒内输入以下字符串 :");
String str = work_01();
System.out.println(str);
new Thread(seelp).start();
String input = scanner.nextLine();
if (!Objects.equals(str, input)){
System.out.println("输入不匹配!");
System.exit(1);
}else {
System.out.println("输入正确,通过!");
System.exit(1);
}
}
static String work_01() throws InterruptedException {
Random random = new Random();
Work_01 work_01 = new Work_01();
Work_01.len = random.nextInt(5)+5;
Thread thread1 = new Thread(work_01);
Thread thread2 = new Thread(work_01);
Thread thread3 = new Thread(work_01);
thread1.start();
thread2.start();
thread3.start();
thread1.join();
thread2.join();
thread3.join();
while (true){
if (Work_01.len==0){
break;
}
}
return Work_01.str;
}
}
结果: