package 第十四周实验; import 第十四周实验.EX9_2.DelayRunnable; public class EX9_2 { class DelayRunnable implements Runnable { private int count = 0; private int no; private int delay; public DelayRunnable() { count++; no = count; } public void run() { try { for (int i = 0; i < 10; i++) { delay = (int) (Math.random() * 5000); Thread.sleep(delay); System.out.println("线程" + no + " 的延迟时间是 " + delay); } } catch (InterruptedException e) { } } } } class MyThread { public static void main(String args[]) { DelayRunnable runnable1 = new DelayRunnable(); DelayRunnable runnable2 = new DelayRunnable(); Thread thread1 = new Thread(runnable1); Thread thread2 = new Thread(runnable2); thread1.start(); thread2.start(); try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.println("线程出错!"); } } }出现了No enclosing instance of type EX9_2 is accessible. Must qualify the allocation with an enclosing instance of type EX9_2 (e.g. x.new A() where x is an instance of EX9_2).问题,请你修改代码使其正确
时间: 2023-11-27 17:51:41 浏览: 126
ex.zip_JSP在线人数统计_ex
将DelayRunnable类声明为静态内部类即可解决该问题。修改代码如下:
```
package 第十四周实验;
public class EX9_2 {
static class DelayRunnable implements Runnable {
private static int count = 0;
private int no;
private int delay;
public DelayRunnable() {
count++;
no = count;
}
public void run() {
try {
for (int i = 0; i < 10; i++) {
delay = (int) (Math.random() * 5000);
Thread.sleep(delay);
System.out.println("线程" + no + " 的延迟时间是 " + delay);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String args[]) {
DelayRunnable runnable1 = new DelayRunnable();
DelayRunnable runnable2 = new DelayRunnable();
Thread thread1 = new Thread(runnable1);
Thread thread2 = new Thread(runnable2);
thread1.start();
thread2.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("线程出错!");
}
}
}
```
阅读全文