
网上没有搜到这道PTA的题,自己就做了一下,总是只通过一个测试点,最后我发现原本来是我在线程的run()方法中没有按要求把标志位flag改为true,PTA的判断中应该是判断了Flag的值,来判断我们有没有正常关闭进程。
目录
裁判测试程序:
输入样例:
输出样例:
实现代码如下:
某科学机构为了搜索外星人,准备使用多线程技术。当线程发现传入的关键字包含alien时则输出相关信息。
定义一个MonitorTask类实现Runnable接口,包含:
属性:
private boolean flag = false; //用于停止线程的标志位,可根据需要自行决定是否使用其他关键字修饰flag
private String word;
方法:
public void stopMe(); //用来终止线程。
public void sendWord(String word) //将入参word赋值给属性word。
run() //持续监测属性word,一旦发现属性word包含alien,则输出。 输出代码为: System.out.println(Thread.currentThread().getName()+" found alien in "+word)
注: 对每个传入的word只检查一遍(检查完后将word置为null)。跳出无限循环后,使用 System.out.println(Thread.currentThread().getName() + " stop") 打印标识信息。
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws InterruptedException {
MonitorTask task1 = new MonitorTask();
Thread t1 = new Thread(task1);
t1.start();
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String word = sc.next();
if (word.equals("stop")) {
task1.stopMe();
} else if (word.equals("quit")) {
break;
} else {
if (t1.isAlive())
task1.sendWord(word);
}
Thread.sleep(10);
}
System.out.println(t1.isAlive());
task1.stopMe();
sc.close();
}
}
输入样例:
def alien abc defalien stop quit输出样例:
x found alien in alien x found alien in defalien x stop //这里是System.out.println(t1.isAlive());的输出结果
输出样例说明: x的值为Thread.currentThread().getName()输出的值。
实现代码如下:class MonitorTask implements Runnable{
private volatile boolean flag = false;
private String word;
public void stopMe() {
this.flag = true;
}
public void sendWord(String word) {
this.word = word;
}
public void run() {
while(!flag) {
if(word!=null&&word.contains("alien")) {
System.out.println(Thread.currentThread().getName()+" found alien in "+word);
word = null;
}
}
System.out.println(Thread.currentThread().getName() + " stop");
stopMe();
}
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)