线程编程,输入输入并停止"hello world"输入并一直输入另一个输入,直到您输入"quit"?

  • 本文关键字:另一个 quit world 编程 线程 hello java
  • 更新时间 :
  • 英文 :


这是一个将打印出"你好,世界"每隔三秒钟。你会得到一个输入框来写一条消息,但我如何才能停止消息";你好,世界"当我输入新输入时?每次我写一条新消息,之前的消息也会停止写吗?例如:控制台输出:你好,世界!你好,世界!你好,世界!赢(然后我输入Win!并停止Hello世界!(赢(Win每三秒持续一次,直到我输入另一个输入文本(。微笑(新输入:微笑和"胜利!"停止。

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()方法来停止线程。这种方法是不安全的,已被弃用。这解释了为什么以及应该使用什么。

相关内容

最新更新