java - 线程程序,输入一个输入并停止“hello world”输入并一直输入另一个输入,直到输入“quit”?
问题描述
这是一个将打印出“Hello world!”的程序。每三秒钟。你会得到一个输入框来写一条消息,但是我怎样才能停止消息“Hello world!” 当我输入一个新的输入?并且每次我写一条新消息之前的消息也会停止写吗?例如:控制台输出:Hello World!你好世界!你好世界!赢!(然后我输入 Win! 并停止 Hello world!) 赢!(每三秒赢一次,直到我输入另一个输入文本)。微笑!(新输入:微笑和“赢!”停止。
public class Main {
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new myThread());
Thread t2 = new Thread(new inputThread());
t1.start();
t2.start();
t1.join();
t2.join();
}
}
public class myThread implements Runnable {
private boolean stop = false;
public synchronized void stop() {
this.stop = true;
}
private synchronized boolean continues() {
return this.stop == false;
}
@Override
public void run() {
while(continues()) {
System.out.println("Hello world!");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
}
}
}
}
public class inputThread implements Runnable {
private boolean stop = false;
public synchronized void stop() {
this.stop = true;
}
private synchronized boolean continues() {
return this.stop == false;
}
@Override
public void run() {
while(continues()) {
String message = showInputDialog("Write your message, type quit to shut down!");
if(message.equals("quit")) {
break;
}
else {
System.out.println(message);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
}
}
}
}
}
解决方案
Thread API曾经有一个方法stop()
来停止线程。此类方法不安全,已被弃用。这解释了为什么以及应该使用什么。
推荐阅读
- sql - 额外的 XML 数据键值对到 SQL
- python - 将列表项拆分为单独的列 - 熊猫数据框
- java - 是否可以从坐标生成对 JButton 的引用?
- java - 如何在包含 magisk 应用程序的根设备中限制我的 android 应用程序?
- android - 在 Play Store / App Store 购买后触发 HTTP 请求
- c# - 为什么 NLog 在控制器中工作而不在 Program.cs 中工作?
- php - Laravel 'belongsTo' 关系不起作用,不知道为什么
- asp.net-core - 将自定义模型类添加到 Swagger 文档
- python - 计算numpy数组中一行中重复元素的数量
- azure - 基于路径的作业条件