package cn.sundragon.heima2;import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;public class TraditionalTimerTest {
public static void main(String[] args) {
class MyTimerTask extends TimerTask {
public void run() {
x = (x + 1) % 2;
System.out.println("炸弹");
new Timer().schedule(new MyTimerTask(), 2000 + 2000 * x);
}
}
// new Timer().schedule(new MyTimerTask(), 2000);
Timer timer = new Timer();
timer.schedule(new Bob(), 2000);
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(new Date().getSeconds());
}
}
static class Bobing extends TimerTask {
public void run() {
System.out.println(" Bob");
new Timer().schedule(new Bob(), 4000);
}
}
static class Bob extends TimerTask {
public void run() {
System.out.println(" Bob");
new Timer().schedule(new Bobing(), 2000);
}
}
private static int x =0;
}
先上代码,有点疑问,我在main方法中
Timer timer = new Timer();
timer.schedule(new Bob(), 2000);
的时候,调用的类Bob为什么需要加上static才行
然后在main方法中 把Timer timer = new Timer();
timer.schedule(new Bob(), 2000); 放到while循环后,却提示错误呢?
2处疑问,还请大家指点迷津下
谢谢了
import java.util.Timer;
import java.util.TimerTask;public class TraditionalTimerTest {
public static void main(String[] args) {
class MyTimerTask extends TimerTask {
public void run() {
x = (x + 1) % 2;
System.out.println("炸弹");
new Timer().schedule(new MyTimerTask(), 2000 + 2000 * x);
}
}
// new Timer().schedule(new MyTimerTask(), 2000);
Timer timer = new Timer();
timer.schedule(new Bob(), 2000);
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(new Date().getSeconds());
}
}
static class Bobing extends TimerTask {
public void run() {
System.out.println(" Bob");
new Timer().schedule(new Bob(), 4000);
}
}
static class Bob extends TimerTask {
public void run() {
System.out.println(" Bob");
new Timer().schedule(new Bobing(), 2000);
}
}
private static int x =0;
}
先上代码,有点疑问,我在main方法中
Timer timer = new Timer();
timer.schedule(new Bob(), 2000);
的时候,调用的类Bob为什么需要加上static才行
然后在main方法中 把Timer timer = new Timer();
timer.schedule(new Bob(), 2000); 放到while循环后,却提示错误呢?
2处疑问,还请大家指点迷津下
谢谢了
a. 静态内部类 (有static修饰的内部类)的对象创建时不依赖于它的外部类对象
b. 普通内部类的对象创建时需要依赖于它的外部类对象,例如在你的例子中把Bob 前面的static去掉时,
创建一个Bob对象的方法如下: TraditionalTimerTest t = new TraditionalTimerTest(); TraditionalTimerTest.Bob b = t.new Bob();2. 如果是因为点1的错误的话,当然会提示有错误,如果点1中的Bob是静态内部类的话,把Timer的创建放在while循环里是不会有错的
1 为什么 TraditionalTimerTest.Bob b = t.new Bob(); 这个t.net Bob(); t指向的new对象究竟是从哪里出来的?
2 我在1楼的代码中,把Timer timer = new Timer();
timer.schedule(new Bob(), 2000); 放到while循环后,却提示错误呢? 放到了while循环是不会错,但是为什么会不会错呢? 放到了while循环外面的后面却会提示错误