急!!!!大家帮忙解决一下!!!!
Class Test{
public void a(){
System.out.println( "a method is running ");
}
public void b(){
for(int i=0;;i++){
System.out.println(i+ "is running ");
}
}
public static void main(String[] args){
//如何让a()每两秒执行一次,穿插在b()的执行结果中
}
}
我想得到的结果是:
a method is running
1 is running
2 is running
3 is running
......//2秒后再次执行a()
a method is running
140 is running
141 is running
......//2秒后再次执行a()
a method is running
270 is running
271is running
....//2秒后再次执行a()
------解决方案--------------------class Test{
public void a(){
System.out.println( "a method is running ");
}
public void b(){
for(int i=0;;i++){
System.out.println(i+ "is running ");
//还是小睡一会吧,否则打得太快,眼花瞭乱的,你根本啥也看不清。
try { Thread.sleep(200); } catch(Exception e) {};
}
}
public static void main(String[] args){
//如何让a()每两秒执行一次,穿插在b()的执行结果中
final Test t = new Test();
new Thread(new Runnable() {
public void run() {
t.b();
}
}).start();
new Thread(new Runnable(){
public void run() {
while(true) {
t.a();
try { Thread.sleep(2000); } catch(Exception e) {};
}
}
}).start();
}
}
------解决方案--------------------内部类访问的局部变量必需声明为final最终类型
new Thread(new Runnable() {
public void run() {
t.b(); // 访问的局部变量
}
}).start();