它是一个简单的java线程。
有2个线程,应该每5秒打印一次
没有错误。
但是我不能跑
请帮我找出错误...
class MyThread extends Thread {
String message;
int delay;
public MyThread(String s, int d) {
message = s;
delay = d;
}
public void run() {
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
System.out.println(message + "+" + delay );
}
}
}
public class applet {
public static void main(String[] args){
MyThread mt1, mt2;
mt1 = new MyThread("Hello", 5000);
mt2 = new MyThread("Bye ", 10000);
mt1.start();
mt2.start();
}
}
答案 0 :(得分:1)
如果发生异常,您正在打印 ONLY ONCE ...
将run
方法修改为:
public void run() {
try {
Thread.sleep(delay);
System.out.println(message + "+" + delay );
} catch (InterruptedException e) {
System.err.println("error here" );
}
}
答案 1 :(得分:1)
您的计划实际上有2
个错误:
到目前为止,只有当你得到一个InterruptedException
时才会打印你的消息,这是一个异常,当你的线程在休眠时被打断时会被抛出。因此,不应在catch块中打印您的消息,而是应该在sleep
之后打印它:
try {
Thread.sleep(delay);
System.out.println(message + "+" + delay );
} catch (InterruptedException e) {
// Re-set the interrupted flag
Thread.currentThread().interrupt();
}
由于您希望每5秒打印一次消息,您需要在无限循环中调用sleep
,否则您的线程只打印一次并死掉,所以代码应该在最后:
try {
while (true) {
Thread.sleep(delay);
System.out.printf("%s+%d%n", message, delay);
}
} catch (InterruptedException e) {
// Re-set the interrupted flag
Thread.currentThread().interrupt();
}
或者,您可以使用ScheduledExecutorService
使用方法scheduleAtFixedRate
以固定费率安排任务,您的代码将是:
// Create a ScheduledExecutorService of 2 threads
ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
// Schedule my task every 5 seconds starting in 5 seconds
executor.scheduleAtFixedRate(new MyTask("Hello", 5000), 5L, 5L, TimeUnit.SECONDS);
// Schedule my task every 10 seconds starting in 10 seconds
executor.scheduleAtFixedRate(new MyTask("Bye ", 10000), 10L, 10L, TimeUnit.SECONDS);
班级MyTask
只是:
class MyTask implements Runnable {
String message;
int delay;
public MyTask(String s, int d) {
message = s;
delay = d;
}
public void run() {
System.out.printf("%s+%d%n", message, delay);
}
}