我正在创建一个打印三个铃声的程序。
当用户在键盘上键入一个键时,我需要停止该过程,我该怎么办?
此外,我会确保每个铃声随机显示您的声音,并使用属性Math.random()
。您可以将随机时间与线程相关联吗?
package campane;
import java.io.*;
import java.util.*;
public class GestioneCampane extends Thread {
public static void main(String [] args) {
BufferedReader tast = new BufferedReader(new InputStreamReader(System.in));
char pressione;
Campane campana = new Campane("DIN", 300);
Campane campana2 = new Campane("DON", 1000);
Campane campana3 = new Campane("DAN", 2000);
campana.start();
campana2.start();
campana3.start();
}
}
这是第二类
package campane;
public class Campane extends Thread {
private String campane; // word to print
private int delay;
public Campane(String whatToSay, int delayTime) {
campane = whatToSay;
delay = delayTime;
}
public void run() {
try {
while(true) {
System.out.print(campane + " ");
Thread.sleep(delay);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:0)
您可以通过中断线程来停止线程:
Thread.interrupt()
您可以在给定时间内停止线程,并在消耗时间后继续使用该线程:
Long time = 15000L; // in milliseconds
Thread.sleep(time);
使用KeyBindings拦截按下的按键并将您的声音随机化,this example can save time